[英]WPF: Command on Canvas doesn't work
我正在MVVM
實現一個簡單的Tetris
游戲。 主面板是Canvas
。 我想使用鍵盤箭頭進行導航。 為此,我實現了MoveLeftCommand
和MoveRightCommand
。 這些命令綁定到KeyBinding
內部的ViewModel
。
在我的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(); }
}
靈魂不起作用。
在調試模式下,當我按向左或向右箭頭鍵時,執行甚至不會進入CanExecute
方法。 它的行為就像不知道命令一樣。
我還嘗試過將注意力集中在Canvas
。 沒有結果。 我嘗試的另一件事是以不同的方式實現命令。 也沒有結果。
然而,當我添加了一個簡單的Textbox
的頂部Canvas
,並實現了在相同的命令Textbox
就開始工作了-我可以使用箭頭導航游戲。
知道為什么Canvas
上的命令被忽略了嗎?
謝謝
我認為您的問題是由一個簡單的初始化問題引起的。
之所以無效,是因為綁定是在創建RoutedCommand對象之前進行的。
將命令屬性替換為以下實現:
private RelayCommand moveRightCommand;
public RelayCommand MoveRightCommand
{
get
{
if (moveRightCommand == null)
{
moveRightCommand = new RelayCommand(MoveRight);
moveRightCommand.GestureKey = Key.Right;
}
return moveRightCommand;
}
}
或者,您可以按照自己的方式創建它們,並在Command的屬性上引發PropertyChanged事件。
private RelayCommand moveRightCommand;
public RelayCommand MoveRightCommand
{
get
{
return moveRightCommand;
}
set
{
moveRightCommand = value;
PropertyChanged(this, new PropertyChangedEventArgs("MoveRightCommand"));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.