cod*_*oop 21 c# wpf xaml commandbinding
我的WPF应用程序中有一个搜索字段,其中包含一个包含命令绑定的搜索按钮.这很好用,但是当按下键盘上的Enter键时,如何对文本字段使用相同的命令绑定?我见过的例子都是使用KeyDown事件处理程序后面的代码.有没有一种聪明的方法可以使用xaml和命令绑定来完成这项工作?
Dab*_*rnl 24
您可以使用按钮的IsDefault属性:
<Button Command="SearchCommand" IsDefault="{Binding ElementName=SearchTextBox,
Path=IsKeyboardFocused}">
Search!
</Button>
Run Code Online (Sandbox Code Playgroud)
Gre*_*som 24
只有在您已经有一个绑定到该命令的按钮时,才能使用已接受的答案.
要避免此限制,请使用TextBox.InputBindings:
<TextBox.InputBindings>
<KeyBinding Key="Enter" Command="{Binding Path=MyCommand}"></KeyBinding>
</TextBox.InputBindings>
Run Code Online (Sandbox Code Playgroud)