Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why ObservableCollection is not updated on items change?

I noticed that ObservableCollection in WPF reflects changes in GUI only by adding or removing an item in the list, but not by editing it.

That means that I have to write my custom class MyObservableCollection instead. What is the reason for this behaviour?

Thanks

like image 957
theSpyCry Avatar asked Jul 16 '09 09:07

theSpyCry


2 Answers

The ObservableCollection has no way of knowing if you make changes to the objects it contains - if you want to be notified when those objects change then you have to make those objects observable as well (for example by having those objects implement INotifyPropertyChanged)

like image 55
Justin Avatar answered Sep 29 '22 16:09

Justin


another way of achieving this would be that you implement a new XXXViewModel class that derives from DependencyObject and you put this one in the ObservableCollection.

for this look at this very good MVVM introduction: http://blog.lab49.com/archives/2650

an example for such a class would be:

public class EntryViewModel : DependencyObject
{
    private Entry _entry;
    public EntryViewModel(Entry e)
    {
        _entry = e;
        SetProperties(e);
    }

    private void SetProperties(Entry value)
    {

        this.Id = value.Id;
        this.Title = value.Title;
        this.CreationTimestamp = value.CreationTimestamp;
        this.LastUpdateTimestamp = value.LastUpdateTimestamp;
        this.Flag = value.Flag;
        this.Body = value.Body;
    }


    public Entry Entry
    {
        get {
            SyncBackProperties();
            return this._entry;
        }
    }


    public Int64 Id
    {
        get { return (Int64)GetValue(IdProperty); }
        set { SetValue(IdProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Id.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty IdProperty =
        DependencyProperty.Register("Id", typeof(Int64), typeof(EntryViewModel), new UIPropertyMetadata(new Int64()));

}}

important things here: - it derives from DependencyObject - it operates with DependencyProperties to support WPFs databinding

br sargola

like image 27
Sargola Avatar answered Sep 29 '22 17:09

Sargola