我使用这段代码来模拟我的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中做到这一点?
您可以创建一个Behavior (System.Windows.)在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;
}
}
不幸的是,在XAML中没有直接的方法来做到这一点。在后面代码中编写的事件处理程序必须是实例方法,而不能是静态方法。这些方法必须由由x: class标识的CLR名称空间中的部分类定义。您不能限定事件处理程序的名称,以指示XAML处理器在不同的类作用域中查找事件连接的事件处理程序。