当我们按 Enter 键时启动的 WPF 文本框命令
将 WPF 应用程序中的 Button
绑定到 VIEWMODEL
类中的 Command
非常容易。我想为 TextBox
实现类似的绑定。
我有一个 TextBox
,我需要将其绑定到一个 Command
,当我按下 Enter 时,该命令会启动,而 TextBox
> 重点突出。目前,我正在使用以下处理程序来处理 KeyUp
事件,但它看起来很丑...... 我无法将其放入我的 VIEWMODEL 类中。
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!");
}
}
有更好的方法吗?
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
.
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!");
}
}
Is there a better way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我遇到了同样的问题并找到了解决方案 这里,这是代码示例:
I've faced with the same problem and found solution here, here is the code sample:
Aryan,并非每个 WPF 对象都支持命令。因此,如果您不想这样做,则需要从后面的代码调用视图模型(有点耦合),或者使用一些 MVVM 消息传递实现来解耦。有关示例,请参阅 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:
我喜欢 Sarh 的答案,但它在我的程序中不起作用,除非我将
Enter
更改为Return
:I like Sarh's answer, but it wouldn't work in my program, unless I changed
Enter
toReturn
:我从此处获取答案
I took answer from here
您可以将 AcceptReturn 属性设置为 true。
You can set true to AcceptReturn property.