我正在实现一个简单的 Tetris
游戏在MVVM
.主面板是Canvas
.我想使用键盘箭头导航。为此,我实现了 MoveLeftCommand
和 MoveRightCommand
.命令绑定(bind)到 ViewModel
里面 KeyBinding
.
下面是我的xaml
执行
<Canvas
Width="{Binding Width}"
Height="{Binding Height}"
>
<Canvas.InputBindings>
<!-- One type of implementation -->
<KeyBinding Key="{Binding MoveLeftCommand.GestureKey}"
Command="{Binding MoveRightCommand}"/>
<!-- Different style of implementation -->
<KeyBinding Key="{Binding MoveLeftCommand.GestureKey}"
Command="{Binding MoveLeftCommand}"/>
</Canvas.InputBindings>
...
</Canvas>
命令在
ViewModel
中初始化的构造函数。public RelayCommand MoveRightCommand { get; set; }
public RelayCommand MoveLeftCommand { get; set; }
public GamePanelViewModel()
{
this.MoveLeftCommand = new RelayCommand(new Action(MoveLeft));
this.MoveLeftCommand.GestureKey = Key.Left;
this.MoveRightCommand = new RelayCommand(new Action(MoveRight));
this.MoveRightCommand.GestureKey = Key.Right;
}
这是命令实现:
public class RelayCommand : ICommand
{
private Action action;
public Key GestureKey { get; set; }
public RelayCommand(Action action) { this.action = action; }
public bool CanExecute(object parameter) { return true; }
public event EventHandler CanExecuteChanged;
public void Execute(object parameter) { this.action(); }
}
灵魂不工作。
在 Debug模式下,当我按向左或向右箭头键时,执行甚至从未进入
CanExecute
方法。它的行为就好像它不知道这些命令一样。我也尝试过强制关注
Canvas
.没有结果。我尝试的另一件事是以不同的方式实现命令。也没有结果。
但是,当我添加了一个简单的
Textbox
在 Canvas
之上,并在 Textbox
上实现了相同的命令它开始起作用了——我可以用箭头来导航游戏。知道为什么
Canvas
上的命令被忽略了?谢谢
最佳答案
我认为您的问题源于一个简单的初始化问题。
没有任何效果的原因是绑定(bind)发生在创建 RoutedCommand 对象之前。
用以下实现替换您的命令属性:
private RelayCommand moveRightCommand;
public RelayCommand MoveRightCommand
{
get
{
if (moveRightCommand == null)
{
moveRightCommand = new RelayCommand(MoveRight);
moveRightCommand.GestureKey = Key.Right;
}
return moveRightCommand;
}
}
或者,您可以按照自己的方式创建它们,并提出 属性已更改 指挥部属性(property)上的事件。
private RelayCommand moveRightCommand;
public RelayCommand MoveRightCommand
{
get
{
return moveRightCommand;
}
set
{
moveRightCommand = value;
PropertyChanged(this, new PropertyChangedEventArgs("MoveRightCommand"));
}
}
关于c# - WPF: Canvas 上的命令不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24222650/