Window.InputBindings with associated collection

I can not find anything like this on the Internet. I am looking for a way to create a collection of Keybindings in code (using Keybinding ViewModel) and then bind the collection to a view, instead of listing all the bindings manually in Xaml.

I expect it to look something like this.

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

and then in the code, there is a list. Is such an approach possible? Where to begin?

+4
source share
1 answer

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

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 for any UIElement :

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

If you want to be very interested, you can enter INotifyCollectionChanged and update InputBindings if the collection changes, but you will need to unsubscribe from the old collection, and therefore you need to be more careful with this.

+6
source

All Articles