KeyBinding不能与RelayCommand一起使用

时间:2016-03-15 15:31:24

标签: wpf c#-4.0

我正在使用稍微调整RelayCommand来将命令指向我的视图模型,这样可以正常工作,但出于某种原因,我根本无法获得输入绑定。例如,我有一个这样的菜单:

<Grid DataContext="{StaticResource app}">
...
    <MenuItem Header="_Run" IsEnabled="{Binding HasScript}">
        <MenuItem Header="_Run" Command="{ Binding RunCommand }" Style="{StaticResource menuEnabledStyle}" InputGestureText="F5"/>
        ...
    </MenuItem>
</Grid>

单击菜单项(显然)时运行正常,但我在此处定义了快捷方式:

<Window.InputBindings>
    <KeyBinding Key="F5"
                Command="{Binding RunCommand}"/>
    <KeyBinding Modifiers="Alt" Key="F4"
                Command="ApplicationCommands.Close"/>
</Window.InputBindings>

但是点击F5什么都不做(作为参考,对ApplicationCommands.Close的绑定工作正常)。没有绑定错误(如果我更改它以绑定不存在的FooCommand我立即得到绑定错误)并且我无法弄清楚它在这里缺少什么。

我的命令在我的视图模型中定义如下:

private RelayCommand _runCommand;
public ICommand RunCommand
{
    get
    {
        if (_runCommand == null)
        {
            _runCommand = new RelayCommand(p => { this.CurrentScript.Run(); }, p => this.CurrentScript != null && !this.CurrentScript.IsRunning);
        }
        return _runCommand;
    }
}

1 个答案:

答案 0 :(得分:2)

Command的Binding没有数据上下文(好吧,它使用的是windows,但没有设置)。所以,你必须指定它。

以下是我完成的完整的工作测试案例:

XAML:

[HttpGet] 
Public ActionResult CheckAuthentication(string username, string pass)
{
  // Your code to check the Authentication
  int count = _dbcontext.modal.toList(r => r.Username == username && r. password == pass).toList().Count; 
  if(count == 1)
  {
     return JSON("Authenticated",JsonRequestBehaviour.AllowGet);
  }
  else
  {
     return JSON("Failed");
   }
}


[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }
// Remove all this stuff as we could achieve the same in AJAX request
}

CS:

<Window x:Class="WpfApplication30.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication30"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <local:VM x:Key="app" />
    </Window.Resources>
    <Window.InputBindings>
        <KeyBinding Key="F5" Command="{Binding RunCommand, Source={StaticResource app}}" />
    </Window.InputBindings>
    <Grid DataContext="{StaticResource app}">
        <Menu>
            <MenuItem Header="_File">
                <MenuItem Header="_Run" Command="{Binding RunCommand}" InputGestureText="F5" />
            </MenuItem>
        </Menu>
    </Grid>
</Window>