1

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

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

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

请注意,由于问题 2,使用某种布尔值来跟踪“加载”状态将不起作用。

我究竟做错了什么?有任何想法吗?

4

3 回答 3

2

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

<Window.CommandBindings>
  <CommandBinding Command="Cancel" Executed="CancelExecuted" />
</Window.CommandBindings>

<Window.InputBindings>
  <KeyBinding Command="Cancel" Key="C" Modifiers="Alt"/>
</Window.InputBindings>
于 2009-11-06T16:06:54.430 回答
1

看起来这是标准行为。(嘘!)

WPF 加速键,如 Visual Studio

http://blogs.msdn.com/saraford/archive/2004/04/16/114935.aspx

于 2009-11-06T15:56:20.477 回答
1

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

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

这是一个关于如何实现这样一个命令的非常快速和 hacky 的演示。

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
}
于 2009-11-06T15:59:04.637 回答