在分配新值后,将ObservableCollection绑定到DataGrid

Mas*_*sha 3 data-binding datagrid observablecollection silverlight-3.0

这似乎是一个简单的问题,但我无法让它发挥作用.

我有一个UserControl具有以下属性:

public ObservableCollection<HL7Message> source {get; set;}
Run Code Online (Sandbox Code Playgroud)

以下绑定:

<data:DataGrid x:Name="dgMessages" Grid.Row="2" AutoGenerateColumns="True" 
ItemsSource="{Binding source}" ></data:DataGrid>
Run Code Online (Sandbox Code Playgroud)

来自父UserControl我在按钮点击时设置值:

messagesGrid.source = src; //messagesGrid is the name of the UserCntrol above
Run Code Online (Sandbox Code Playgroud)

我期待我的DataGrid会更新,但事实并非如此.你能指出我做错了什么吗?

HCL*_*HCL 5

遗憾的是,自动属性不支持更改通知.因此,如果设置source-Property ,DataGrid将不会知道集合已更改.

一种可能性是为-Property 实现INotifiyPropertyChangedmessagesGrid.source:

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");
            } 
        }
  } 
  ....
Run Code Online (Sandbox Code Playgroud)

请注意,我已经Source在UpperCase中写了第一个字母,因为在.net中,属性通常是这样写的.您必须相应地更改绑定,因为绑定区分大小写.

<data:DataGrid x:Name="dgMessages" Grid.Row="2" AutoGenerateColumns="True"  ItemsSource="{Binding Source}" ></data:DataGrid> 
Run Code Online (Sandbox Code Playgroud)