绑定到键绑定手势
本文关键字:绑定 | 更新日期: 2023-09-27 17:52:16
我正在尝试设置一个输入手势,如下所示:
<Window.InputBindings>
<KeyBinding Command="{Binding MyCommand}" Gesture="{x:Static local:Resources.MyCommandGesture}" />
</Window.InputBindings>
这里的资源是一个资源。resx文件和MyCommandGesture是其中定义的字符串。这会产生以下异常:
无法强制转换System类型的对象。String to type System.Windows.Input.InputGesture.
如果我只是用资源文件中的字符串替换绑定(例如Gesture="F2"),则没有问题。有什么建议吗?
编辑:我们可以在后面的代码中实现期望的结果,方法如下:
KeyGestureConverter kgc = new KeyGestureConverter();
KeyGesture keyGestureForMyCommand = (KeyGesture)kgc.ConvertFromString(Resources.MyCommandGesture);
this.InputBindings.Add(new KeyBinding(VM.MyCommand, keyGestureForMyCommand));
我希望找到一个XAML解决方案。
这不起作用,因为您需要将System.Windows.Input.Key枚举中的有效值放入KeyBinding的Gesture属性中。
如果你这样做:
Gesture="F2"
…尽管感觉像是放入了一个字符串,但实际上您放入了一个来自枚举的有效命名常量,因此它可以工作。
但是,如果你使用这个:
Gesture="{x:Static local:Resources.MyCommandGesture}"
它绕过枚举映射,因为你使用x:Static标记扩展,最终说"这是一个字符串"。即使该值等于"Key" enum中的一个有效常量名,它也不会工作。
如果您真的不能接受将键名放在XAML中,我个人不会使用资源文件。相反,我将有一个类将它们定义为正确的类型,即KeyGestures:
public class KeyGestures
{
public static KeyGesture KeyCommandAction1 { get { return new KeyGesture(Key.F1); } }
public static KeyGesture KeyCommandAction2 { get { return new KeyGesture(Key.F2); } }
}
并在XAML中相应地使用:
<KeyBinding Command="{Binding MyCommand1}" Gesture="{x:Static local:KeyGestures.KeyCommandAction1}" />
<KeyBinding Command="{Binding MyCommand2}" Gesture="{x:Static local:KeyGestures.KeyCommandAction2}" />