Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

wpf - Window.InputBindings with a bound collection

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.

I would expect it to look something like this

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

An example:

// 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);
    }
}

This can be used on any UIElement:

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...