You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

绑定到键盘输入的Command无法触发问题求助

WPF MVVM Community Toolkit中键盘绑定命令无法触发的问题

我在学习项目中使用MVVM Community Toolkit(v8.2)实现Risk桌游,自定义按钮的Command可以正常工作,但绑定到键盘输入的Command始终无法触发(断点从未命中),无法定位原因。我曾考虑焦点问题,但即使显式设置Window.Focusable=True,或将InputBindings放在背景图片、自定义按钮等子元素上,问题仍存在。查阅了大量相关解决方案,均无法解决此特定问题。相关代码如下:

MainWindow视图XAML

<Window x:Class="RiskMVVM2.MainWindow"
        ...
        Width="1820" Height="1062" 
        ResizeMode="NoResize" Name="GameWindow"
        WindowStartupLocation="CenterScreen" WindowStyle="None"
        FontFamily="Courier New" FontSize="12" >

    <Window.InputBindings>
        <KeyBinding Key="Return" Command="{Binding ConfirmInputCommand}" />
        <KeyBinding Gesture="Shift+Return" Command="{Binding SkipPlayerTurnCommand}" />
    </Window.InputBindings>

MainWindow构造函数(代码后置)

public MainWindow(RiskBoardVM VM, List<Brush> playerColors)
{
     this.DataContext = VM;

     ...

     InitializeComponent();

     ...
}

相关ViewModel代码

...
     private bool CanConfirmInput()
     {
          return true;
     }

     [RelayCommand(CanExecute = nameof(CanConfirmInput))]
     private void ConfirmInput()
     {
         CurrentGame.State.IncrementPhase();
     }

     private bool CanSkipPlayerTurn()
     {
         if ((int)CurrentPhase > (int)GamePhase.Place) return true;
         else return false;
     }


     [RelayCommand(CanExecute = nameof(CanSkipPlayerTurn))]
     private void SkipPlayerTurn()
     {
         CurrentGame.State.IncrementPlayerTurn();
     }
...

内容的提问来源于stack exchange,提问作者jmcknight00

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 00:02:44