简体   繁体   English

键绑定-RelayCommand在xaml.cs中

[英]KeyBinding - RelayCommand is in xaml.cs

I bind my textboxes to ViewModel class. 我将文本框绑定到ViewModel类。 But, button command (it's a RelayCommand, extended from ICommand) I bind to UsersView.xaml.cs. 但是,我绑定到UsersView.xaml.cs的按钮命令(这是RelayCommand,是ICommand的扩展)。 In UsersView.xaml.cs constructor I have this: 在UsersView.xaml.cs构造函数中,我具有以下内容:

DataContext = UserVM;
btnAdd.DataContext = this;

This is how I bind button - it works. 这就是我绑定按钮的方式-它起作用。

<Button Command="{Binding Add}" Content="Add user" />

Now, I want to add KeyGesture for that button but I can't set DataContext for InputBindings and compiler can't find this Add command in UsersVM class. 现在,我想为该按钮添加KeyGesture,但无法为InputBindings设置DataContext,并且编译器在UsersVM类中找不到此Add命令。

<UsersView.InputBindings>
    <KeyBinding Key="F10" Command="{Binding Add}" />
</UsersView.InputBindings>

I had this on a Window and this is the code I used... 我在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">

Notice that I set the x.Name of the Window. 注意,我设置了窗口的x.Name Then in my KeyBinding, I did this... 然后在我的KeyBinding中,我做了这个...

<Window.InputBindings>

    <KeyBinding
        Key="F10"
        Command="{Binding ElementName=MyMainWindow, Path=DataContext.AddPersonCommand}" />

</Window.InputBindings>

The AddPersonCommand is my ICommand from my ViewModel. AddPersonCommand是我的ViewModel中的ICommand。

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

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