【问题标题】:WPF hot key firing without modifier没有修饰符的WPF热键触发
【发布时间】:2010-12-13 21:11:32
【问题描述】:

我有一个 WPF 窗口,其中包含一个名为“取消”的按钮。在一般情况下,我希望用户能够按 Alt+C 取消他们的操作并关闭程序。因此,该按钮的标题为“_Cancel”。

问题 1:在 Window_Load 期间,如果我在没有修饰符的情况下按 C,则会触发 Cancel_Clicked 事件,并且程序会关闭。

问题2:我的程序打开后,假设我没有与窗口上的任何东西交互,按C不带修饰符将关闭程序。

请注意,由于问题 2,使用某种布尔值来跟踪“加载”状态是行不通的。

我做错了什么?有什么想法吗?

【问题讨论】:

    标签: wpf window load hotkeys


    【解决方案1】:
    【解决方案2】:

    我发现这与 WinForms 中的行为相同。 (直到我创建了一个测试项目来尝试它之前,我都不敢相信!)。这是之前遇到的相同场景的 SO 问题:WPF Accelerator Keys like Visual Studio

    如果您想强制热键始终使用 Alt 修饰符触发,您可以考虑将操作重构为命令。

    这里有一个关于如何实现这样一个命令的非常快速和简单的演示。

    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            this.InputBindings.Add(new KeyBinding(new DoActionCommand(() => DoIt()), new KeyGesture(Key.C, ModifierKeys.Alt)));
        }
    
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            DoIt();
        }
    
        private void DoIt()
        {
            MessageBox.Show("Did It!");
        }
    
    }
    
    public class DoActionCommand : ICommand
    {
        private Action _executeAction;
    
        public DoActionCommand(Action executeAction)
        {
            _executeAction = executeAction;
        }
        #region ICommand Members
    
        public bool CanExecute(object parameter)
        {
            return true;
        }
    
        public event EventHandler CanExecuteChanged;
    
        public void Execute(object parameter)
        {
            if (_executeAction != null)
            {
                _executeAction.Invoke();
            }
        }
    
        #endregion
    }
    

    【讨论】:

      【解决方案3】:

      您最好的解决方案是将其重构为 command:

      <Window.CommandBindings>
        <CommandBinding Command="Cancel" Executed="CancelExecuted" />
      </Window.CommandBindings>
      
      <Window.InputBindings>
        <KeyBinding Command="Cancel" Key="C" Modifiers="Alt"/>
      </Window.InputBindings>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-01
        • 1970-01-01
        • 2015-11-17
        • 2011-02-15
        • 1970-01-01
        相关资源
        最近更新 更多