KeyBinding - RelayCommand is in xaml.cs
本文关键字:xaml cs in is RelayCommand KeyBinding | 更新日期: 2023-09-27 18:08:30
我将我的文本框绑定到ViewModel类。但是,按钮命令(它是一个RelayCommand,从iccommand扩展)我绑定到UsersView.xaml.cs。在usersview . example .cs构造函数中,我有这个:
DataContext = UserVM;
btnAdd.DataContext = this;
这是我如何绑定按钮-它的工作原理。
<Button Command="{Binding Add}" Content="Add user" />
现在,我想为那个按钮添加KeyGesture,但我不能为InputBindings设置DataContext,编译器在UsersVM类中找不到这个add命令。
<UsersView.InputBindings>
<KeyBinding Key="F10" Command="{Binding Add}" />
</UsersView.InputBindings>
我在一个窗口上有这个,这是我使用的代码…
<Window
x:Class="MVVMExample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:myViewModels="clr-namespace:MVVMExample"
Title="MainWindow"
x:Name="MyMainWindow"
Height="350"
Width="525">
注意我设置了窗口的x.Name
。然后在我的KeyBinding中,我这样做了…
<Window.InputBindings>
<KeyBinding
Key="F10"
Command="{Binding ElementName=MyMainWindow, Path=DataContext.AddPersonCommand}" />
</Window.InputBindings>
AddPersonCommand
是我的iccommand从我的ViewModel。