Bind ObservableCollection to a DataGrid after assigning new value

7.2k views Asked by At

It seems to be a simple problem, but I can't get it to work.

I have a UserControl with the following property:

public ObservableCollection<HL7Message> source {get; set;}

And the following Binding:

<data:DataGrid x:Name="dgMessages" Grid.Row="2" AutoGenerateColumns="True" 
ItemsSource="{Binding source}" ></data:DataGrid>

from a parent UserControl I set the value upon a button click:

messagesGrid.source = src; //messagesGrid is the name of the UserCntrol above

I'm expecting my DataGrid to be updated, but it's not. Can you please point at what I'm doing wrong?

2

There are 2 answers

5
HCL On BEST ANSWER

Auto-properties sadly do not support change-notification. Therefore the DataGrid will not know that the collection has been changed if you set the source-Property.

One possibility is to implement INotifiyPropertyChanged for the messagesGrid.source-Property:

class YourUserControlClass: INotifyPropertyChanged

  public event PropertyChangedEventHandler PropertyChanged;

  protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) {    
    if (null != PropertyChanged) {        
           PropertyChanged(this,e);    
    }
  }

  ObservableCollection<HL7Message> m_source;

  public ObservableCollection<HL7Message> Source { g
        get{return m_source;}
        set{
            if(value != m_source){
                 m_source=value;
                 OnPropertyChanged("Source");
            } 
        }
  } 
  ....

Please note, I have written the first letter of Source in UpperCase because in .net, properties are generally written so. You have to change your binding accordingly because Bindings are case sensitive.

<data:DataGrid x:Name="dgMessages" Grid.Row="2" AutoGenerateColumns="True"  ItemsSource="{Binding Source}" ></data:DataGrid> 
2
devdigital On

The problem is that when the reference for source changes on your button click, there is nothing to tell the UI to update itself. You will either need to make source a dependency property, or implement INotifyPropertyChanged, and invoke the PropertyChanged event in the setter for source.

private ObservableCollection<HL7Message> source;
public ObservableCollection<HL7Message> Source 
{ 
  get
  {
    return this.source;
  }

  set
  {
    this.source = value;
    this.NotifyPropertyChanged(() => this.Source);
  }
}