我在 WPF 中构建了一个继承自 ListBox 的自定义控件。在此我实现了我自己的属性,即 BindingList。为了使该属性可绑定(bind),我将其实现为 DependencyProperty:
public BindingList<CheckableListItem> CheckedItems
{
get
{
return (BindingList<CheckableListItem>)GetValue(MultiComboBox.CheckedItemsProperty);
}
set
{
SetValue(MultiComboBox.CheckedItemsProperty, value);
}
}
public static readonly DependencyProperty CheckedItemsProperty;
我在自定义控件内的静态构造函数中注册此 DependencyProperty:
CheckedItemsProperty = DependencyProperty.Register("CheckedItems",
typeof(BindingList<CheckableListItem>),
typeof(MultiComboBox),
new FrameworkPropertyMetadata(new BindingList<CheckableListItem>()));
(MultiComboBox 是我的自定义控件的名称。CheckableListItem 是我为此目的编写的一个简单类)。
当用户与自定义控件交互时,此 BindingList 将在自定义控件内部(从不在外部)更新。
当我在 XAML 中使用自定义控件时,我以“OneWayToSource”模式绑定(bind)到 CheckItems 属性。我正在使用 MVVM 模式,并且我绑定(bind)到的 ViewModel 中的属性也是一个 BindingList。 ViewModel 永远不会影响此列表,它只会对自定义控件对列表所做的更改使用react。 ViewModel 中的属性如下所示:
private BindingList<CheckableListItem> _selectedItems;
public BindingList<CheckableListItem> SelectedItems
{
get
{
return _selectedItems;
}
set
{
if (value != _selectedItems)
{
if (_selectedItems != null)
{
_selectedItems.ListChanged -= SelectedItemsChanged;
}
_selectedItems = value;
if (_selectedItems != null)
{
_selectedItems.ListChanged += SelectedItemsChanged;
}
OnPropertyChanged("SelectedItems");
}
}
}
正如您所看到的,我正在监听对列表所做的更改(这些更改始终发生在我的自定义控件内),并在“SelectedItemsChanged”方法中相应地更新我的模型。
现在...当我的 View 中有这些控件之一时,这非常有用。但是,如果我将其中两个(或更多)放在同一个 View 中,奇怪的事情就会开始发生。这当然意味着我的 ViewModel 中将有两个包含选定项目的列表。但是,如果在 View 中执行某些更改其中一个列表的操作,则两个列表都会受到影响!也就是说,如果对其中任何一个列表进行更改,则两个列表都会触发事件 ListChanged 的事件处理程序!
有人认识到这个问题和/或有解决方案吗?我的实现有什么问题?
我的第一点是 DependencyProperty 是静态的。通常这意味着在所有实例之间共享。但我猜 DependencyProperties 以其他一些“神奇”的方式工作,所以这可能不是问题。
如有任何提示或提示,我们将不胜感激!
最佳答案
我在集合类型依赖属性上遇到了类似的问题。我的解决方案取自MSDN文章Collection-Type Dependency Properties 。它添加了以下行
SetValue(OperatorsPropertyKey, new List<ListBoxItem>()); //replace key and type
在我的控件的构造函数中,因为无论包含此集合的控件有多少个实例,集合类型依赖属性构造函数似乎都只会被调用一次(静态呃)。
关于WPF:使用控件的多个实例时,自定义控件的 DependencyProperty 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4815632/