ObservableCollection dependency property does not update when item in collection is deleted

后端 未结 3 1026
眼角桃花
眼角桃花 2020-12-09 02:58

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 collecti

3条回答
  •  爱一瞬间的悲伤
    2020-12-09 03:47

    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)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
    }
    

提交回复
热议问题