Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVVM / ObservableCollection Question

I have the following XAML:

   <Grid x:Name="LayoutRoot">
        <sdk:DataGrid AutoGenerateColumns="True" Margin="46,38,0,40" x:Name="FamilyListGrid" HorizontalAlignment="Left" Width="475" 
               ItemsSource="{Binding FamilyList}"
               SelectedItem="{Binding SelectedFamily, Mode=TwoWay}" />
    </Grid>

My FamilyList property used in the Binding is an ObservableCollection of entities in my view model class. I'm finding that I need to implement INotifyPropertyChanged in the setter of my FamilyList collection or the binding doesn't work. It was my understanding that an ObservableCollection already implemented this. If this is the case, why do I need to implement the notify property?

If it helps, here is my FamilyList property definition:

    private ObservableCollection<Services.Family> familyList;
    public ObservableCollection<Services.Family> FamilyList
    {
        get { return familyList; }
        private set 
        { 
            familyList = value;
            NotifyPropertyChanged("FamilyList");
        }
    }
like image 902
Randy Minder Avatar asked Dec 29 '22 00:12

Randy Minder


1 Answers

ObservableCollection<T> implements INotifyCollectionChanged which informs a registered event handler about changes in the collection (add,remove,sort of items). However the DataGrid must know if a property of one of your business-objects has changed to update the value in the grid. For this, INotifyPropertyChanged is needed.
ObservableCollection<T> implements also INotifyCollectionChanged. However this can only be used to be informed if a property of the collection has been changed. There is no mechanism that let the collection detect if your business object has been changed (and if it would have, it would register to INotifyCollectionChanged of your business object :).

like image 137
HCL Avatar answered Jan 05 '23 12:01

HCL