我在网上找不到任何看起来像这样的东西。我正在寻找一种在代码中创建键绑定(bind)集合的方法(使用键绑定(bind) ViewModel),然后将集合绑定(bind)到 View ,而不是在 Xaml 中手动列出每个绑定(bind)。
我希望它看起来像这样
<Window.InputBindings ItemsSource="{Binding Path=KeybindingList}" />
然后在代码中,有一个列表。这种方法可行吗?我从哪里开始?
最佳答案
您可以创建一个 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
如果集合发生变化,但您需要取消订阅旧集合等,因此您需要更加小心。
关于wpf - 带有绑定(bind)集合的 Window.InputBindings,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9385129/