本文介绍了创建关键在WPF结合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要创建输入窗口结合
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>
如果我初始化SomeCommand一些CustomCommand:ICommand的它不火。 SomeCommand属性的get()不会被调用。
If i init SomeCommand with some CustomCommand:ICommand it doesn't fire. SomeCommand property get() 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>
.....
后面的代码:
Code behind:
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结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!