【发布时间】:2016-03-15 15:31:23
【问题描述】:
我正在使用稍微改编的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;
}
}
【问题讨论】:
-
你必须在你的 ViewModel 构造函数中初始化你的命令,你可以有一个
private set -
@XAMlMAX:当您第一次尝试访问它时,它会延迟初始化(在
get中) -
我也遇到过类似的问题,一旦我在构造函数中初始化它,一切都开始工作了。
-
@XAMlMAX:好的,我会试一试。编辑:似乎没有帮助。不过谢谢你的建议。
-
@J.H.:碰巧我还有一个没有
canExecute的那个也不起作用_openCommand = new RelayCommand(p => this.Open());