将KeyBinding的键绑定到Key属性

时间:2015-08-02 21:07:37

标签: c# wpf key-bindings

我试图将KeyBinding的Key属性绑定到Key属性,如下所示:

<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是Key类型的属性。

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属性?

1 个答案:

答案 0 :(得分:1)

<强>更新

我在我的解决方案中犯了一个错误,但由于我不得不努力提供一个有效的解决方案,这就是我的建议:

首先,使用InputBindingTrigger的{​​{1}}属性时,自定义Binding似乎不允许ActionMessage

因此,由于Caliburn.Micro已经在使用InputBindingTrigger,为什么不省略ICommand,只使用简单的Caliburn.Micro命令?

<强>的Xaml:

KeyBinding

<强> MainWindow.cs:

<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>

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