在后面的代码中将命令绑定到KeyBinding [英] Bind Command to KeyBinding in Code Behind

查看:104
本文介绍了在后面的代码中将命令绑定到KeyBinding的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的应用程序中添加一些通用的键盘快捷键。当前,在每个View XAML中,我都添加以下代码:

I want to add some generic keyboard shortcuts to my application. Currently, in every View XAML I add this code:

<Window.InputBindings>
    <KeyBinding Command="{Binding ZoomInCommand}" Key="Add" Modifiers="Control" />
    <KeyBinding Command="{Binding ZoomOutCommand}" Key="Subtract" Modifiers="Control" />
</Window.InputBindings>

我想对此进行概括,我想对WPF窗口类进行子类化,而改用新创建的子类。现在,我想知道如何将这些键盘命令绑定到相应的代码中。当前看起来像这样:

I order to generalize this, I want to subclass the WPF Window Class and use the newly created subclass instead. Now I'm wondering how I could bind these Keyboard commands in the corresponding code. Currently it looks like this:

public class MyWindow : Window
{
    public MyWindow()
    {
        DataContextChanged += OnDataContextChanged;
    }

    private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
    {
        InputBindings.Clear();
        var dataContext = DataContext as IZoomableViewModel;
        if (dataContext != null)
        {
            InputBindings.Add(new KeyBinding(dataContext.ZoomInCommand, Key.Add, ModifierKeys.Control));
            InputBindings.Add(new KeyBinding(dataContext.ZoomOutCommand, Key.Subtract, ModifierKeys.Control));
        }
    }
}

但这看起来并不对我来说,因为我需要直接访问DataContext并对其进行强制转换,而不是使用Binding()对象。我该如何更改代码以使其看起来更像MVVM?

But this doesn't look right to me, as I need to have access to the DataContext directly and cast it instead of using a Binding() Object. How can I change the code to make it look more MVVM-like?

推荐答案

我找到了一个简单的解决方案,该解决方案效果很好,似乎模仿XAML解析器行为。基本上,为了实现放大功能,我将以下代码放入MyWindow构造函数中:

I found a simple solution which works nicely and seems to imitate the XAML parser behavior. Basically, for the zoom in functionality I put the following code in the MyWindow constructor:

var zoomInKeyBinding = new KeyBinding { Key = Key.Add, Modifiers = ModifierKeys.Control };
BindingOperations.SetBinding(
    zoomInKeyBinding,
    InputBinding.CommandProperty,
    new Binding { Path = new PropertyPath("ZoomInCommand") }
);
InputBindings.Add(zoomInKeyBinding);

当然,绑定的ViewModel需要适当地实现ZoomInCommand。

Of course the bound ViewModel needs to implement the ZoomInCommand appropriately.

这篇关于在后面的代码中将命令绑定到KeyBinding的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆