我一直在寻找一个解决方案,但提出的方案似乎过于复杂。所以,这里提供了一种新的双向绑定方案,它仅限于一个附加属性,并使用弱事件处理来监视定义的依赖属性的更改。我没有花费任何时间来完善它,但它确实起作用。
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;
}
}
}
}