【问题标题】:Window.InputBindings with a bound collection带有绑定集合的 Window.InputBindings
【发布时间】:2012-03-12 05:02:46
【问题描述】:

我在网上找不到类似的东西。我正在寻找一种在代码中创建键绑定集合的方法(使用键绑定 ViewModel),然后将集合绑定到视图,而不是在 Xaml 中手动列出每个绑定。

我希望它看起来像这样

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

然后在代码中,有一个列表。这种方法可行吗?我该从哪里开始?

【问题讨论】:

    标签: wpf xaml data-binding collections key-bindings


    【解决方案1】:

    您可以创建一个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 但您需要取消订阅旧集合,因此您需要更加小心那个。

    【讨论】:

    • 要修改窗口,您需要在代码隐藏中执行此操作,对吗?我正在尝试这样做以保持 MVVM 模式。
    • @Tyrsius:不在window的代码中,可以在任何类中,就像在绑定中使用值转换器,与MVVM无关。
    • @Tyrsius:我添加了一个示例来说明该方法。
    猜你喜欢
    • 2013-05-29
    • 2014-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多