您还可以创建一个通用行为,可以轻松应用于应用程序中的任何文本框.这是一个示例行为类: –
public class TextBoxEnterKeyUpdateBehavior : Behavior
{
protected override void OnAttached()
{
if (this.AssociatedObject != null)
{
base.OnAttached();
this.AssociatedObject.KeyDown += AssociatedObject_KeyDown;
}
}
protected override void OnDetaching()
{
if (this.AssociatedObject != null)
{
this.AssociatedObject.KeyDown -= AssociatedObject_KeyDown;
base.OnDetaching();
}
}
private void AssociatedObject_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
TextBox textBox = sender as TextBox;
if (textBox != null)
{
if (e.Key == Key.Return)
{
if (e.Key == Key.Enter)
{
textBox.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
}
}
}
}
}
要在xaml中使用此类,只需将其包含在文本框行为集合中,如下所示: –
这里“i”指的是System.Windows.Interactivity命名空间.