我有一个自定义控件,它具有 ObservableCollection
类型的 DependencyProperty
绑定(bind)到 observableCollection
:
<MyControl MyCollectionProperty = {Binding MyObservableCollection} ...
问题是添加到 MyObservableCollection
不会更新 MyCollectionProperty
。
我需要完全替换 MyObservableCollection
以使其正常工作,例如
MyObservableCollection = null;
MyObservableCollection = new ObservableCollection(){...}
有没有更好的方法来处理这个问题?
编辑:
public ObservableCollection<string> Columns
{
get { return (ObservableCollection<string>)GetValue(ColumnsProperty); }
set { SetValue(ColumnsProperty, value); }
}
public static readonly DependencyProperty ColumnsProperty =
DependencyProperty.Register("Columns", typeof(ObservableCollection<string>), typeof(MyControl),
new PropertyMetadata(new ObservableCollection<string>(), OnChanged));
最佳答案
除了 grantz 的回答之外,我建议声明类型为 IEnumerable<string>
的属性。并在运行时检查集合对象是否实现了 INotifyCollectionChanged
界面。这为可以将哪个具体集合实现用作属性值提供了更大的灵 active 。然后,用户可以决定拥有自己的可观察集合的专门实现。
另请注意,在 ColumnsPropertyChanged
中回调CollectionChanged
事件处理程序附加到新集合,但也从旧集合中删除。
public static readonly DependencyProperty ColumnsProperty =
DependencyProperty.Register(
"Columns", typeof(IEnumerable<string>), typeof(MyControl),
new PropertyMetadata(null, ColumnsPropertyChanged));
public IEnumerable<string> Columns
{
get { return (IEnumerable<string>)GetValue(ColumnsProperty); }
set { SetValue(ColumnsProperty, value); }
}
private static void ColumnsPropertyChanged(
DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var control= (MyControl)obj;
var oldCollection = e.OldValue as INotifyCollectionChanged;
var newCollection = e.NewValue as INotifyCollectionChanged;
if (oldCollection != null)
{
oldCollection.CollectionChanged -= control.ColumnsCollectionChanged;
}
if (newCollection != null)
{
newCollection.CollectionChanged += control.ColumnsCollectionChanged;
}
control.UpdateColumns();
}
private void ColumnsCollectionChanged(
object sender, NotifyCollectionChangedEventArgs e)
{
// optionally take e.Action into account
UpdateColumns();
}
private void UpdateColumns()
{
...
}
关于c# - 集合依赖属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15015217/