将 KeyBinding 的 Key 绑定到 Key 属性

Bind Key of KeyBinding to Key Property

我正在尝试将 KeyBinding 的键 属性 绑定到键 属性,如下所示:

<i:Interaction.Triggers>
    <local:InputBindingTrigger>
        <local:InputBindingTrigger.InputBinding>
            <KeyBinding Key="{Binding SettingsViewModel.PreviousHotkey}"/>
        </local:InputBindingTrigger.InputBinding>
        <cal:ActionMessage MethodName="FormKeyDown"/>
    </local:InputBindingTrigger>
</i:Interaction.Triggers>

PreviousHotkey 是 属性 键类型。

public Key PreviousHotkey
{
    get { return _previousHotkey; }
    set { _previousHotkey = value; }
}

据我了解,KeyBindings 是应用程序范围的,所以哪个控件具有焦点应该无关紧要吧? 当我执行时,输出中出现以下错误:

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=SettingsViewModel.PreviousHotkey; DataItem=null; target element is 'KeyBinding' (HashCode=24311996); target property is 'Key' (type 'Key')

也好像不行。

如何绑定 KeyBinding 的 Key 属性?

更新

我的解决方案有误,但由于我有义务至少努力提供一个可行的解决方案,因此我的建议如下:

首先,似乎自定义InputBindingTrigger在使用Caliburn.MicroActionMessage属性时不允许Binding

因此,既然 InputBindingTrigger 已经在使用 ICommand,为什么不省去 Caliburn.Micro 而只使用带有命令的简单 KeyBinding

Xaml:

<Window x:Class="MainWindow">
    <Window.InputBindings>
        <KeyBinding Key="{Binding MyKey}" Command="{Binding MyCommand}" 
            CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Key}"/>
    </Window.InputBindings>
    <Grid>
        ...
    </Grid>
</Window>

MainWindow.cs:

    public ICommand MyCommand { get; set; }

    Key _myKey ;
    public Key MyKey 
    {
        get
        {
            return _myKey;
        }
        set
        {
            _myKey = value;
            OnPropertyChanged("MyKey");
        }
    }

    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
        MyCommand = new KeyCommand(MyMethod);
        MyKey =  Key.F5;
    }

    public void MyMethod(object param)
    {
        var inputKey = param;
        // do something
    }

KeyCommand的实现:如果您还没有实现类似的东西。

public class KeyCommand : ICommand
{
    Action<object> _execute;
    public event EventHandler CanExecuteChanged = delegate { };
    public KeyCommand(Action<object> execute)
    {
        _execute = execute;
    }
    public bool CanExecute(object parameter)
    {
        return true;
    }

    public void Execute(object param)
    {
        _execute(param);
    }
}