开发者

Why does UpdateSourceTrigger occur when changing ObservableCollection but not replacing it?

I am just starting out with WPF and am trying to understand data binding.

In my project I have a listbox bound to a property, which gets/sets from a DependancyProperty.

If I this property is an ObservableCollection (and I set UpdateSourceTrigger to PropertyChanged) my listbox correctly represents the content of the collection and updates with it. When I swap out the collection entirely for a new one though, it no longer updates.

Why is this? Does the listbox become bound t开发者_如何学编程o that specific object permanently? Should SetValue() in the Set accessor not cause it to bind to the new one, and update accordingly?


UpdateSourceTrigger only affects when the source is updated from changes in the control. It has nothing to do with what you do with the object on its own.

I greatly discourage you from overwriting the reference to the collection because any event handlers which also need the CollectionChanged event of the collection will need to be reconnected.

I am not sure how notifications are handled if you bind to dependency properties, but if you change your source and it is not a DP you need to notify the binding. This can be done by implementing INotifyPropertyChanged.

e.g.

    private ObservableCollection<Stuff> data = new ObservableCollection<Stuff>();
    public ObservableCollection<Stuff> Data
    {
        get { return data ; }
        set
        {
            data = value;
            NotifyPropertyChanged("Data");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

Edit: Tested swapping a collection that is stored in a DP, for me it works as expected and the List gets updated, displaying the new collection.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜