问题描述
我在控件上具有类型为ObservableCollection的附加属性.如果我从集合中添加或删除项目,则ui不会更新.但是,如果我用新的ViewModel替换其中的集合,则ui确实会更新.
I have a attached property of type ObservableCollection on a control. If I add or remove items from the collection, the ui does not update. However if I replace the collection within with a new one the ViewModel the ui does update.
有人可以给我一个示例,说明我需要在Dependency对象中执行哪些操作,以便它可以处理集合中的更改吗?
Can someone give me an example of what I need to do within the Dependency object so that it can handle changes within the collection?
下面列出了部分依赖项对象:
Part of the dependency object is listed below:
public class RadCalendarBehavior : DependencyObject
{
private static void OnSpecialDaysChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var calendar = d as RadCalendar;
if (e.NewValue != null)
{
calendar.DayTemplateSelector = new SpecialDaySelector((ObservableCollection<DateTime>)e.NewValue, GetSpecialDayTemplate(d));
}
}
public static ObservableCollection<DateTime> GetSpecialDays(DependencyObject obj)
{
return (ObservableCollection<DateTime>)obj.GetValue(SpecialDaysProperty);
}
public static void SetSpecialDays(DependencyObject obj, ObservableCollection<DateTime> value)
{
obj.SetValue(SpecialDaysProperty, value);
}
public static readonly DependencyProperty SpecialDaysProperty =
DependencyProperty.RegisterAttached("SpecialDays", typeof(ObservableCollection<DateTime>), typeof(RadCalendarBehavior), new UIPropertyMetadata(null, OnSpecialDaysChanged));
}
}
我了解我需要注册该集合已更改,但是我不确定如何在依赖项属性中执行此操作
I understand that I need to register that the collection has changed, but I am unsure how to do this within the dependency property
推荐答案
集合中的更改不会触发OnSpecialDaysChanged
回调,因为dependency属性的值未更改.如果您需要做出反应以检测集合中的更改,则需要手动处理事件CollectionChanged
事件:
A change within the collection won't trigger the OnSpecialDaysChanged
callback, because the value of the dependency property hasn't changed. If you need to react to detect changes with the collection, you need to handle the event CollectionChanged
event manually:
private static void OnSpecialDaysChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var calendar = d as RadCalendar;
if (e.OldValue != null)
{
var coll = (INotifyCollectionChanged)e.OldValue;
// Unsubscribe from CollectionChanged on the old collection
coll.CollectionChanged -= SpecialDays_CollectionChanged;
}
if (e.NewValue != null)
{
var coll = (ObservableCollection<DateTime>)e.NewValue;
calendar.DayTemplateSelector = new SpecialDaySelector(coll, GetSpecialDayTemplate(d));
// Subscribe to CollectionChanged on the new collection
coll.CollectionChanged += SpecialDays_CollectionChanged;
}
}
private static void SpecialDays_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
// handle CollectionChanged
}
这篇关于删除集合中的项目时,ObservableCollection依赖项属性不会更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!