WPF 绑定依赖关系 属性 到 ObservableCollection
WPF Binding Dependency Property to ObservableCollection
我有一个具有依赖性的用户控件 属性:
public static readonly DependencyProperty MasterListProperty = DependencyProperty.Register("MasterList", typeof(IEnumerable<MyObject>), typeof(MyControl), new FrameworkPropertyMetadata(null, new PropertyChangedCallback(MasterListChanged)));
我的对象实现了 INotifyPropertyChanged。我正在尝试将此依赖项 属性 绑定到该对象的 ObservableCollection
。但是,当我将此依赖项 属性 绑定到的项目添加到我的根集合时,我没有得到任何更新。
这是将此依赖项 属性 绑定到我的集合的控件:
<image:MyControl MasterList="{Binding Path=SourceList, UpdateSourceTrigger=PropertyChanged}"></image:MyControl>
我已经尝试放置 Mode=TwoWay
,但我的依赖项 属性 仍然没有得到任何更新。我有一个绑定到依赖项 属性 计数的工具提示,它得到更新,但是我的 MasterListChanged
事件没有被触发。
有什么想法吗?
however I'm not getting any update when I add an item to my root collection that this dependency property is bound to.
你不应该这样做。依赖项 属性 的 PropertyChangedCallback
仅在依赖项 属性 自身 设置为新值时调用。将 MyObject
添加到源集合时不会调用它。
你可以做的是处理集合的 CollectionChanged
事件,如果你想在添加或删除项目时做一些事情,例如:
private static void MasterListChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var newCol = e.NewValue as INotifyCollectionChanged;
if (newCol != null)
{
newCol.CollectionChanged += Coll_CollectionChanged;
}
var oldCol = e.OldValue as INotifyCollectionChanged;
if (oldCol != null)
{
oldCol.CollectionChanged -= Coll_CollectionChanged;
}
}
private static void Coll_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
//do something...
}
我有一个具有依赖性的用户控件 属性:
public static readonly DependencyProperty MasterListProperty = DependencyProperty.Register("MasterList", typeof(IEnumerable<MyObject>), typeof(MyControl), new FrameworkPropertyMetadata(null, new PropertyChangedCallback(MasterListChanged)));
我的对象实现了 INotifyPropertyChanged。我正在尝试将此依赖项 属性 绑定到该对象的 ObservableCollection
。但是,当我将此依赖项 属性 绑定到的项目添加到我的根集合时,我没有得到任何更新。
这是将此依赖项 属性 绑定到我的集合的控件:
<image:MyControl MasterList="{Binding Path=SourceList, UpdateSourceTrigger=PropertyChanged}"></image:MyControl>
我已经尝试放置 Mode=TwoWay
,但我的依赖项 属性 仍然没有得到任何更新。我有一个绑定到依赖项 属性 计数的工具提示,它得到更新,但是我的 MasterListChanged
事件没有被触发。
有什么想法吗?
however I'm not getting any update when I add an item to my root collection that this dependency property is bound to.
你不应该这样做。依赖项 属性 的 PropertyChangedCallback
仅在依赖项 属性 自身 设置为新值时调用。将 MyObject
添加到源集合时不会调用它。
你可以做的是处理集合的 CollectionChanged
事件,如果你想在添加或删除项目时做一些事情,例如:
private static void MasterListChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var newCol = e.NewValue as INotifyCollectionChanged;
if (newCol != null)
{
newCol.CollectionChanged += Coll_CollectionChanged;
}
var oldCol = e.OldValue as INotifyCollectionChanged;
if (oldCol != null)
{
oldCol.CollectionChanged -= Coll_CollectionChanged;
}
}
private static void Coll_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
//do something...
}