Bind ObservableCollection to a DataGrid after assigning new value

谁说胖子不能爱 提交于 2019-12-10 10:34:28

问题


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?


回答1:


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:


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);
  }
}


来源:https://stackoverflow.com/questions/4998255/bind-observablecollection-to-a-datagrid-after-assigning-new-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!