在 WPF 中创建键绑定 [英] Create Key binding in WPF
本文介绍了在 WPF 中创建键绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要为 Window 创建输入绑定.
I need to create input binding for 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>
如果我用一些 CustomCommand : ICommand
初始化 SomeCommand
它不会触发.SomeCommand
属性 getter 永远不会被调用.
If I init SomeCommand
with some CustomCommand : ICommand
it doesn't fire. SomeCommand
property getter is never called.
推荐答案
对于你的情况最好使用 MVVM 模式
For your case best way used MVVM pattern
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
的实现.这个简单有用的课程.
Then you'll need an implementation of ICommand
.
This simple helpful class.
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;
}
这篇关于在 WPF 中创建键绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文