问题描述
我正在处理一个窗口,我想创建一个不可见的命令(或虚拟的,我不确定它是如何调用的)并且总是自我检查(在运行时总是如此)。这样我就可以用 C# 编写一个脚本代码,我可以用定时器控制。
到目前为止,我只能在 xaml 中找到用于正常事件的常用命令,例如:
<KeyBinding Modifiers="Control" Key="N" Command="{Binding NewCommandFile}" />
。
有可能实现吗?
谢谢
解决方法
不确定这是否是您的要求,但您可以创建自定义命令。例如,运行任意委托的命令:
break
在你的代码隐藏文件中你会写
public class DelegateCommand : ICommand
{
private readonly Action execute;
public DelegateCommand(Action execute) => this.execute = execute;
public bool CanExecute(object parameter) => true;
public void Execute(object parameter) => execute();
public event EventHandler CanExecuteChanged { add{} remove{}}
}
并绑定
public ICommand MyCommand{ get; }
public MyViewModel(){
MyCommand = new DelegateCommand(MyMethod);
}
public void MyMethod(){
// Do whatever
}