带有绑定集合的 Window.InputBindings [英] Window.InputBindings with a bound collection

查看:29
本文介绍了带有绑定集合的 Window.InputBindings的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上找不到类似的东西.我正在寻找一种在代码中创建键绑定集合的方法(使用键绑定 ViewModel),然后将集合绑定到视图,而不是在 Xaml 中手动列出每个绑定.

I can't find anything that looks like this online. I am looking for a way to create a collection of Keybindings in the code (with a Keybinding ViewModel), and then bind the collection to the view, instead of listing out every binding manually in Xaml.

我希望它看起来像这样

<Window.InputBindings ItemsSource="{Binding Path=KeybindingList}" />

然后在代码中,有一个列表.这种方法可行吗?我该从哪里开始?

and then in the code, have a List. Is such an approach possible? Where would I start?

推荐答案

您可以创建一个 附加属性,监听其变化并修改关联窗口的InputBindings集合.

You can create an attached property, listen to its changes and modify the InputBindings collection of the associated window.

示例:

// Snippet warning: This may be bad code, do not copy.
public static class AttachedProperties
{
    public static readonly DependencyProperty InputBindingsSourceProperty =
        DependencyProperty.RegisterAttached
            (
                "InputBindingsSource",
                typeof(IEnumerable),
                typeof(AttachedProperties),
                new UIPropertyMetadata(null, InputBindingsSource_Changed)
            );
    public static IEnumerable GetInputBindingsSource(DependencyObject obj)
    {
        return (IEnumerable)obj.GetValue(InputBindingsSourceProperty);
    }
    public static void SetInputBindingsSource(DependencyObject obj, IEnumerable value)
    {
        obj.SetValue(InputBindingsSourceProperty, value);
    }

    private static void InputBindingsSource_Changed(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        var uiElement = obj as UIElement;
        if (uiElement == null)
            throw new Exception(String.Format("Object of type '{0}' does not support InputBindings", obj.GetType()));

        uiElement.InputBindings.Clear();
        if (e.NewValue == null)
            return;

        var bindings = (IEnumerable)e.NewValue;
        foreach (var binding in bindings.Cast<InputBinding>())
            uiElement.InputBindings.Add(binding);
    }
}

这可以用于任何UIElement:

<TextBox ext:AttachedProperties.InputBindingsSource="{Binding InputBindingsList}" />

如果您希望它非常花哨,可以键入检查 INotifyCollectionChanged 并更新 InputBindings 如果集合更改但您需要取消订阅旧集合等,因此您需要更加小心

If you want it to be very fancy you can type-check for INotifyCollectionChanged and update the InputBindings if the collection changes but you will need to unsubscribe from the old collection and such so you need to be more careful with that.

这篇关于带有绑定集合的 Window.InputBindings的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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