gpt4 book ai didi

c# - 在 xaml 中作为事件处理程序的静态函数

转载 作者:太空狗 更新时间:2023-10-29 22:23:59 25 4
gpt4 key购买 nike

我正在使用 this在我的 silverlight 应用程序中模拟选项卡功能的代码。

我真的很想避免多次编写该函数,因为它必须在整个应用程序的相当多的文本框上使用。我创建了一个静态类

public static class TabInsert
{
private const string Tab = " ";
public static void textBox_KeyDown(object sender, KeyEventArgs e)
{
TextBox textBox = sender as TextBox;
if (e.Key == Key.Tab)
{
int selectionStart = textBox.SelectionStart;
textBox.Text = String.Format("{0}{1}{2}",
textBox.Text.Substring(0, textBox.SelectionStart),
Tab,
textBox.Text.Substring(textBox.SelectionStart + textBox.SelectionLength, (textBox.Text.Length) - (textBox.SelectionStart + textBox.SelectionLength))
);
e.Handled = true;
textBox.SelectionStart = selectionStart + Tab.Length;
}
}
}

这样我就可以从不同的地方访问它,比如这个 textBox.KeyDown += TabInsert.textBox_KeyDown;

我可以在 XAML 中执行此操作吗?

最佳答案

您可以创建一个行为(System.Windows.Interactivity 命名空间)以轻松附加到文本框,在 OnAttached() 覆盖中订阅事件并像您一样进行处理,并在 OnDetaching() 中取消订阅。

类似于:

public class TabInsertBehavior : Behavior<TextBox>
{
/// <summary>
/// Called after the behavior is attached to an AssociatedObject.
/// </summary>
/// <remarks>
/// Override this to hook up functionality to the AssociatedObject.
/// </remarks>
protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.KeyDown += textBox_KeyDown;
}

private const string Tab = " ";
public static void textBox_KeyDown(object sender, KeyEventArgs e)
{
TextBox textBox = sender as TextBox;
if (e.Key == Key.Tab)
{
int selectionStart = textBox.SelectionStart;
textBox.Text = String.Format("{0}{1}{2}",
textBox.Text.Substring(0, textBox.SelectionStart),
Tab,
textBox.Text.Substring(textBox.SelectionStart + textBox.SelectionLength, (textBox.Text.Length) - (textBox.SelectionStart + textBox.SelectionLength))
);
e.Handled = true;
textBox.SelectionStart = selectionStart + Tab.Length;
}
}

/// <summary>
/// Called when the behavior is being detached from its AssociatedObject, but before it has actually occurred.
/// </summary>
/// <remarks>
/// Override this to unhook functionality from the AssociatedObject.
/// </remarks>
protected override void OnDetaching()
{
base.OnDetaching();
this.AssociatedObject.KeyDown -= textBox_KeyDown;
}
}

关于c# - 在 xaml 中作为事件处理程序的静态函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8077556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com