wpf - 带有绑定(bind)集合的 Window.InputBindings

标签 wpf xaml data-binding collections key-bindings

我在网上找不到任何看起来像这样的东西。我正在寻找一种在代码中创建键绑定(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/

相关文章:

c# - Windows 8 - XAML - 将网格放入 ListView

javascript - 我可以在 Web 项目上使用 binding.js 进行数据绑定(bind)吗?

c# - WPF 网。 3.5 C# 对象引用未设置为对象的实例。我该如何解决?

WPF ListView 忽略 SelectedItem 更改

c# - WPF中不规则PNG按钮的点击事件

javascript - 复选框更改时,AngularFire 3 向数据绑定(bind)不会更新 firebase

.net - 如何将数据绑定(bind)到 System.Windows.Forms.Treeview 控件?

wpf - 使用XAML或MVVM将焦点设置为UI元素

c# - 切片图像wpf

c# - Windows Phone 开发错误错误 "Csc.exe"退出,代码为 -1073741819