2011-09-14 24 views
4

我将我的文本框绑定到ViewModel类。但是,按钮命令(这是一个RelayCommand,从ICommand扩展)我绑定到UsersView.xaml.cs。 UsersView.xaml.cs构造函数我有这个:KeyBinding - RelayCommand在xaml.cs中

DataContext = UserVM; 
btnAdd.DataContext = this; 

这是我如何绑定按钮 - 它的工作原理。

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

现在,我想补充KeyGesture该按钮,但我不能化InputBindings设置的DataContext和编译器无法找到这UsersVM类添加命令。

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

你试过了吗?Command =“{Binding Path = DataContext.Add}”'?这是在黑暗中拍摄的,但它可能奏效。 – sellmeadog

+0

不工作。谢谢。 – davor

回答

2

我有这个一个窗口,这是我使用的代码...

<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。然后在我的键绑定,我这样做...

<Window.InputBindings> 

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

</Window.InputBindings> 

AddPersonCommand是我的ICommand从我的ViewModel。

+0

是的,它的工作原理!我设置了x:Name =“MyUsersView”并使用此绑定:。此绑定也适用于按钮命令绑定(从UsersView.xaml构造函数中删除了btnDataContext)。谢谢。 – davor

+1

那么如果它有效,并且您满意,请将其标记为答案。 –