繁体   English   中英

键绑定-RelayCommand在xaml.cs中

[英]KeyBinding - RelayCommand is in xaml.cs

我将文本框绑定到ViewModel类。 但是,我绑定到UsersView.xaml.cs的按钮命令(这是RelayCommand,是ICommand的扩展)。 在UsersView.xaml.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上有这个,这是我使用的代码...

<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是我的ViewModel中的ICommand。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM