WPF TextBox的命令,当我们按Enter键时将触发 [英] Command for WPF TextBox that fires up when we hit Enter Key
问题描述
将WPF应用程序中的 Button
绑定到 Command
非常容易> VIEWMODEL 类。我想为 TextBox
实现类似的绑定。
It is very easy to bind Button
s in WPF apps to Command
s in a VIEWMODEL
class. I'd like to achieve a similar binding for a TextBox
.
我有一个 TextBox
,我需要将其绑定到 Command
,当我按下 Enter 且 TextBox
被重点关注。当前,我在 KeyUp
事件中使用以下处理程序,但是看起来很丑...
,我不能将其放在我的<$ c中$ c> VIEWMODEL 类。
I have a TextBox
and I need to bind it to a Command
that fires up when I hit Enter while the TextBox
is focused. Currently, I'm using the following handler for the KeyUp
event, but it looks ugly...
and I can't put it in my VIEWMODEL
class.
private void TextBox_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == System.Windows.Input.Key.Enter)
{
// your event handler here
e.Handled = true;
MessageBox.Show("Enter Key is pressed!");
}
}
还有更好的方法吗?
推荐答案
Aryan,并非每个WPF对象都支持命令。因此,如果您不想这样做,则需要从后面的代码中调用视图模型(有点耦合),或者使用某些MVVM Messaging实现来解耦。有关示例,请参见 MVVM Light Messaging工具包。或像这样的简单触发器:
Aryan, not every WPF object supports commanding. So if you wan't to do that you'll need either to call your view model from your code behind (a little coupled) or use some MVVM Messaging implementation to decouple that. See MVVM Light Messaging toolkit for an example. Or simple use triggers like this:
<TextBox>
<i:Interaction.Triggers>
<i:EventTrigger EventName="KeyUp">
<i:InvokeDataCommand Command="{Binding MyCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
这篇关于WPF TextBox的命令,当我们按Enter键时将触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!