这似乎是一个简单的问题,但我无法让它工作。
我有一个具有以下属性的 UserControl:
public ObservableCollection<HL7Message> source {get; set;}
以及以下绑定(bind):
<data:DataGrid x:Name="dgMessages" Grid.Row="2" AutoGenerateColumns="True"
ItemsSource="{Binding source}" ></data:DataGrid>
我在父 UserControl 中设置了单击按钮时的值:
messagesGrid.source = src; //messagesGrid is the name of the UserCntrol above
我希望我的 DataGrid 得到更新,但事实并非如此。你能指出我做错了什么吗?
最佳答案
Auto-properties遗憾的是不支持更改通知。因此,如果您设置 source
-Property,DataGrid 将不知道集合已更改。
一种可能性是实现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
的第一个字母写成大写,因为在.net中,属性一般都是这样写的。您必须相应地更改绑定(bind),因为绑定(bind)区分大小写。
<data:DataGrid x:Name="dgMessages" Grid.Row="2" AutoGenerateColumns="True" ItemsSource="{Binding Source}" ></data:DataGrid>
关于data-binding - 分配新值后将 ObservableCollection 绑定(bind)到 DataGrid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4998255/