wpf WPF如何使文本框在按下回车后失去焦点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23613171/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF how to make textbox lose focus after hitting enter
提问by Dess
I created some textboxes and I want user to enter decimal values into them. In every application I have ever used, when I type something into the textbox and hit enter, the value is accepted and textbox lose focus. How can I do it in my app? I know it should be relatively easy to do it with a key event, but maybe there is a command or something. I searched the stackoverflow but I only found questions about how to keep focus after hitting enter...
我创建了一些文本框,我希望用户在其中输入十进制值。在我使用过的每个应用程序中,当我在文本框中键入内容并按 Enter 键时,该值被接受并且文本框失去焦点。我怎样才能在我的应用程序中做到这一点?我知道用一个关键事件来做这件事应该相对容易,但也许有一个命令或其他东西。我搜索了stackoverflow,但我只发现了有关如何在按回车键后保持焦点的问题...
回答by Precog
You can also create a generic behavior which can be easily applied to any textbox within your application. Here is a sample behavior class:-
您还可以创建可轻松应用于应用程序中任何文本框的通用行为。这是一个示例行为类:-
public class TextBoxEnterKeyUpdateBehavior : Behavior<TextBox>
{
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));
}
}
}
}
}
To use this class in your xaml, just include it in textbox behaviors collection like this :-
要在您的 xaml 中使用此类,只需将其包含在文本框行为集合中,如下所示:-
<TextBox>
<i:Interaction.Behaviors>
<TextBoxEnterKeyUpdateBehavior />
</i:Interaction.Behaviors>
</TextBox>
Here "i" refers to System.Windows.Interactivity namespace.
这里的“i”指的是 System.Windows.Interactivity 命名空间。

