我有一个表单,它使用了两次,同一个 UserControl。UserControl 有一个 ListBox,它使用 DependencyProperty 作为 ItemSource(ItemsSource="{Binding Path=Persons, ElementName=ThisControl})。
public static readonly DependencyProperty PersonsProperty = DependencyProperty.Register
(
"Persons",
typeof(ObservableCollection<person>),
typeof(Control),
new FrameworkPropertyMetadata(new ObservableCollection<person>(), OnPersonsChanged)
);
public ObservableCollection<person> Persons
{
get { return (ObservableCollection<person>)GetValue(PersonsProperty); }
set { SetValue(PersonsProperty, value); }
}
private static void OnPersonsChanged(object sender, DependencyPropertyChangedEventArgs e)
{
var me = sender as Control;
var old = e.OldValue as ObservableCollection<person>;
if (old != null) old.CollectionChanged -= me.OnCollectionChanged;
var n = e.NewValue as ObservableCollection<person>;
if (n != null) n.CollectionChanged += me.OnCollectionChanged;
}
private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Reset)
{
Persons.Clear();
}
if (e.NewItems != null)
{
foreach (person item in e.NewItems)
{
item.PropertyChanged += OnPersonChanged;
}
}
if (e.OldItems != null)
{
foreach (person item in e.OldItems)
{
item.PropertyChanged -= OnPersonChanged;
}
}
}
private void OnPersonChanged(object sender, PropertyChangedEventArgs e)
{
}
此 UserControl 使用了多次。这导致该元素被添加到一个 UserControl 的集合中,它显示在所有 UserControl 中。我应该怎么做才能防止这种情况发生?