带有绑定集合的Window.InputBindings

Kye*_*ica 4 data-binding collections wpf xaml key-bindings

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

我希望它看起来像这样

<Window.InputBindings ItemsSource="{Binding Path=KeybindingList}" />
Run Code Online (Sandbox Code Playgroud)

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

H.B*_*.B. 6

您可以创建附加属性,侦听其更改并修改InputBindings关联窗口的集合.

一个例子:

// 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这可用于任何UIElement:

<TextBox ext:AttachedProperties.InputBindingsSource="{Binding InputBindingsList}" />
Run Code Online (Sandbox Code Playgroud)

如果你想要它非常花哨,你可以键入检查INotifyCollectionChanged并更新InputBindings如果集合发生变化,但你需要取消订阅旧集合,这样你就需要更加小心.