我在网上找不到任何类似的内容。我正在寻找一种方法在代码中创建一个Keybindings集合(使用Keybinding ViewModel),然后将集合绑定到视图,而不是在Xaml中手动列出每个绑定。
我希望它看起来像这样
<Window.InputBindings ItemsSource="{Binding Path=KeybindingList}" />
然后在代码中,有一个List。这种方法有可能吗?我从哪里开始?
答案 0 :(得分:6)
您可以创建attached property,收听其更改并修改关联窗口的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);
}
}
这可用于任何UIElement
:
<TextBox ext:AttachedProperties.InputBindingsSource="{Binding InputBindingsList}" />
如果您希望它非常花哨,您可以键入检查INotifyCollectionChanged
并更新InputBindings
如果收集更改但您需要取消订阅旧收藏品,这样您就需要对此更加小心。