17

我一直在尝试查看是否有一种简单/聪明的方法来实现与 ListBox.SelectedItems 的绑定。如果您自己尝试过,您就会知道,使用 BindingExtension 的标记绑定将不起作用——该属性不支持它。因此,您需要为 SelectionChanged 连接一个处理程序并尝试该路线。我得到的最接近的是这篇文章:

http://alexshed.spaces.live.com/blog/cns!71C72270309CE838!149.entry

更新:上面提到的博客不再可用,该作者当前的博客在这里,我能找到的最接近引用的博客文章的是这个 StackOverflow 答案

它在一个方便的附加属性中实现了所有必要的 C#。但它将“绑定”实现为单向、目标到源。我想要双向绑定。

有任何想法吗?

4

2 回答 2

41

我找到了一个优雅的解决方案,我刚刚抽出时间写了一篇关于它的博客文章

我所做的是创建一个附加属性 SynchronizedSelectedItems,您可以在 ListBox(实际上是 DataGrid)上设置它。您将它数据绑定到一个集合,然后,通过一点魔术,ListBox 上的 SelectedItems 属性和您的集合保持同步。您可以从我的博客文章中下载所有代码。

“魔术”是一个类,它侦听任一集合中的 CollectionChanged 事件,并将更改传播到另一个集合。

于 2009-02-12T12:47:12.987 回答
0

我一直在为此寻找解决方案,但提议似乎过于复杂。因此,这是一个新的双向绑定解决方案,它仅限于附加属性,并使用弱事件处理来观察定义的依赖属性的变化。我没有花时间做这个防弹,但它确实有效。


using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Windows;
using System.Windows.Controls;

namespace WpfApplication2
{
    public class ListBoxHelper
    {
        private static Dictionary<int, bool> SynchToDPInProcessDictionary = new Dictionary<int, bool>();
        private static Dictionary<int, bool> SynchToLBInProcessDictionary = new Dictionary<int, bool>();

        public static readonly DependencyProperty SelectedItemsProperty =
            DependencyProperty.RegisterAttached("SelectedItems", typeof(IList), typeof(ListBoxHelper),
                new FrameworkPropertyMetadata((IList)null,
                    new PropertyChangedCallback(OnSelectedItemsChanged)));

        public static IList GetSelectedItems(DependencyObject d)
        {
            return (IList)d.GetValue(SelectedItemsProperty);
        }

        public static void SetSelectedItems(DependencyObject d, IList value)
        {
            d.SetValue(SelectedItemsProperty, value);
        }

        private static void OnSelectedItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var listBox = d as ListBox;
            if (listBox == null) 
                throw new InvalidOperationException("ListBoxHelper should only be used with ListBox or ListBox derived classes (like ListView).");

            int hashcode = listBox.GetHashCode();

            // Gets set on the initial binding.
            if (!SynchToDPInProcessDictionary.ContainsKey(hashcode))
            {
                SynchToDPInProcessDictionary[hashcode] = false;
                SynchToLBInProcessDictionary[hashcode] = false;

                var observableCollection = GetSelectedItems(listBox) as INotifyCollectionChanged;
                if (observableCollection != null)
                {
                    // Create a weak CollectionChanged event handler on the SelectedItems property
                    // that synchronizes the collection back to the listbox.
                    CollectionChangedEventManager.AddHandler(observableCollection,
                        delegate(object sender, NotifyCollectionChangedEventArgs e2)
                        {
                            SyncToLBSelectedItems(GetSelectedItems(d), (ListBox)d);
                        });
                }
            }

            SynchToDPSelectedItems(listBox);
            listBox.SelectionChanged += delegate
            {
                SynchToDPSelectedItems(listBox);
            };
        }


        private static void SynchToDPSelectedItems(ListBox listBox)
        {
            int hashcode = listBox.GetHashCode();
            if (SynchToLBInProcessDictionary[hashcode]) return;

            SynchToDPInProcessDictionary[hashcode] = true;
            try
            {
                IList dpSelectedItems = GetSelectedItems(listBox);
                dpSelectedItems.Clear();
                if (listBox.SelectedItems != null)
                {
                    foreach (var item in listBox.SelectedItems)
                        dpSelectedItems.Add(item);
                }
            }
            finally
            {
                SynchToDPInProcessDictionary[hashcode] = false;
            }
        }

        private static void SyncToLBSelectedItems(IList dpSelectedItems, ListBox listBox)
        {
            int hashcode = listBox.GetHashCode();
            if (SynchToDPInProcessDictionary[hashcode]) return;

            SynchToLBInProcessDictionary[hashcode] = true;
            try
            {
                listBox.SelectedItems.Clear();
                if (dpSelectedItems != null)
                {
                    foreach (var item in dpSelectedItems)
                        listBox.SelectedItems.Add(item);
                }
            }
            finally
            {
                SynchToLBInProcessDictionary[hashcode] = false;
            }
        }
    }
}
于 2014-09-05T21:11:19.283 回答