Ary*_*nsi 72 .net c# wpf icommand
将Button
WPF应用程序中的Command
s 绑定到VIEWMODEL
类中的s 非常容易.我想为a实现类似的绑定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!");
}
}
Run Code Online (Sandbox Code Playgroud)
有一个更好的方法吗?
sar*_*arh 225
我遇到了同样的问题并在这里找到了解决方案,这里是代码示例:
<TextBox>
<TextBox.InputBindings>
<KeyBinding Command="{Binding Path=CmdSomething}" Key="Enter" />
</TextBox.InputBindings>
</TextBox>
Run Code Online (Sandbox Code Playgroud)
Err*_*Efe 20
雅利安,并非每个WPF对象都支持命令.因此,如果您不想这样做,您需要从您的代码后面调用您的视图模型(稍微耦合)或使用一些MVVM消息传递实现来解耦它.有关示例,请参阅MVVM Light Messaging工具包.或者简单的使用触发器如下:
<TextBox>
<i:Interaction.Triggers>
<i:EventTrigger EventName="KeyUp">
<i:InvokeDataCommand Command="{Binding MyCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
Run Code Online (Sandbox Code Playgroud)
Nig*_*mes 12
我喜欢萨尔的答案,但它不会在我的程序工作,除非我改Enter
到Return
:
<TextBox>
<TextBox.InputBindings>
<KeyBinding Key="Return" Command="{}" />
</TextBox.InputBindings>
</TextBox>
Run Code Online (Sandbox Code Playgroud)
小智 7
<TextBox Text="{Binding FieldThatIAmBindingToo, UpdateSourceTrigger=PropertyChanged}">
<TextBox.InputBindings>
<KeyBinding Command="{Binding AddCommand}" Key="Return" />
</TextBox.InputBindings>
</TextBox>
Run Code Online (Sandbox Code Playgroud)
我从这里得到答案