Bind ObservableCollection to DataGrid after assigning a new value

This 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 parent UserControl I set the value when the button is clicked:

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

I expect my DataGrid to be updated, but it is not. Can you indicate what I am doing wrong?

+3
source share
2 answers

Auto properties , unfortunately, do not support change notification. Therefore, the DataGrid will not know that the collection was modified if you installed source-Property.

- INotifiyPropertyChanged 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");
            } 
        }
  } 
  ....

, source UpperCase, .net . , .

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

, source , . source, INotifyPropertyChanged, PropertyChanged source.

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

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

Source: https://habr.com/ru/post/1792108/


All Articles