Bil*_*ell 38 data-binding shortcuts mvvm
我有一个使用MVVM模式的WPF应用程序.将按钮连接到VM非常简单,因为它们实现了ICommand.我有一个类似的上下文菜单.下一步是为上下文菜单创建快捷键.我无法弄清楚如何让快捷键调用Command.这是一个例子:
<MenuItem Header="Update" Command="{Binding btnUpdate}" >
<MenuItem.Icon>
<Image Source="/Images/Update.png"
Width="16"
Height="16" />
</MenuItem.Icon>
</MenuItem>
Run Code Online (Sandbox Code Playgroud)
现在我添加了这个:
<Window.InputBindings>
<KeyBinding Key="U"
Modifiers="Control"
Command="{Binding btnUpdate}" />
</Window.InputBindings>
Run Code Online (Sandbox Code Playgroud)
尝试将快捷键连接到同一个绑定,但这不起作用.错误是:
错误169无法在"KeyBinding"类型的"Command"属性上设置"绑定".'绑定'只能在DependencyObject的DependencyProperty上设置.
有没有办法将此事件连接到命令?我无法弄清楚这一点.
提前致谢!
法案
Mic*_*ers 39
以下代码可用于将快捷键直接绑定到命令:
<Window.InputBindings>
<KeyBinding Command="{Binding Path=NameOfYourCommand}"
Key="O"
Modifiers="Control"/>
</Window.InputBindings>
Run Code Online (Sandbox Code Playgroud)
在View.Xesources之后的视图的XAML代码中添加此项.
Tho*_*que 27
我写了一个自定义标记扩展来"绑定" InputBindings
命令,它几乎可以像真正的绑定一样使用:
<UserControl.InputBindings>
<KeyBinding Modifiers="Control"
Key="E"
Command="{input:CommandBinding EditCommand}"/>
</UserControl.InputBindings>
Run Code Online (Sandbox Code Playgroud)
请注意,此标记扩展使用私有反射,因此只有在应用程序以完全信任的方式运行时才能使用它.
另一种选择是使用CommandReference
该类.它可以在这里提供的MVVM工具包中找到.它可能是一种更清洁的方法,但使用起来有点复杂.
请注意,在WPF 4中InputBinding.Command
,InputBinding.CommandParameter
和InputBinding.CommandTarget
属性是依赖项属性,因此可以正常绑定它们
我同意在XAML中这样做是理想的,但为了完整起见,您还可以在代码中添加绑定.如果你在构造函数中执行它,只需确保它在调用之后InitializeComponent()
InputBindings.Add(new KeyBinding(btnUpdate, new KeyGesture(Key.U, ModifierKeys.Control));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
46014 次 |
最近记录: |