31

我需要为 Window 创建输入绑定。

public class MainWindow : Window
{
    public MainWindow()
    {
        SomeCommand = ??? () => OnAction();
    }

    public ICommand SomeCommand { get; private set; }

    public void OnAction()
    {
        SomeControl.DoSomething();
    }
}

<Window>
    <Window.InputBindings>
        <KeyBinding Command="{Binding SomeCommand}" Key="F5"></KeyBinding>
    </Window.InputBindings>
</Window>

SomeCommand如果我用一些初始化CustomCommand : ICommand它不会触发。SomeCommand永远不会调用属性 getter。

4

5 回答 5

72

对于您的情况,最好的方法是使用 MVVM 模式

XAML:

<Window>
    <Window.InputBindings>
        <KeyBinding Command="{Binding SomeCommand}" Key="F5"/>
    </Window.InputBindings>
</Window>

后面的代码:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
}

在您的视图模型中:

public class MyViewModel
{
    private ICommand someCommand;
    public ICommand SomeCommand
    {
        get
        {
            return someCommand 
                ?? (someCommand = new ActionCommand(() =>
                {
                    MessageBox.Show("SomeCommand");
                }));
        }
    }
}

然后你需要一个ICommand. 这个简单有用的课程。

public class ActionCommand : ICommand
{
    private readonly Action _action;

    public ActionCommand(Action action)
    {
        _action = action;
    }

    public void Execute(object parameter)
    {
        _action();
    }

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public event EventHandler CanExecuteChanged;
}   
于 2013-10-31T09:28:04.263 回答
20

对于修饰符(组合键):

<KeyBinding Command="{Binding SaveCommand}" Modifiers="Control" Key="S"/>
于 2013-11-09T15:52:39.963 回答
4

可能为时已晚,但这是最简单和最短的解决方案。

private void Window_KeyDown(object sender, KeyEventArgs e)
{
    if (Keyboard.Modifiers == ModifierKeys.Control && e.Key == Key.S)
    {
         // Call your method here
    }
}

<Window x:Class="Test.MainWindow" KeyDown="Window_KeyDown" >
于 2019-04-12T06:21:31.877 回答
3

您将必须创建自己的Command实现接口并使用 that 的实例进行ICommand初始化。SomeCommandCommand

现在您必须将DataContextWindow 设置为 self 才能完成Command Binding工作:

public MainWindow()
{
    InitializeComponents();
    DataContext = this;
    SomeCommand = MyCommand() => OnAction();
}

或者你将不得不更新你Binding

 <Window>
   <Window.InputBindings>
    <KeyBinding Command="{Binding SomeCommand, RelativeSource={RelativeSource Self}}" Key="F5"></KeyBinding>
   </Window.InputBindings>
 </Window>
于 2013-10-31T05:46:45.877 回答
0

这就是我在项目中解决这个问题的方法:

<Window x:Class="MyNamespace.MyView"
    (...)
    xmlns:local="clr-namespace:MyNameSpace"
    (...)
    <Grid>
        <Grid.InputBindings>
            <KeyBinding Key="R" Command="{Binding ReportCommand, 
                RelativeSource={RelativeSource AncestorType=local:MyView}}" />
    (...)

ReportCommandICommandin MyView不在ViewModel 中。

于 2020-06-11T09:38:15.733 回答