在指定新值后将ObservableCollection绑定到DataGrid [英] Bind ObservableCollection to a DataGrid after assigning new value

查看:439
本文介绍了在指定新值后将ObservableCollection绑定到DataGrid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是一个简单的问题,但我不能让它工作。

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

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

I have a UserControl with the following property:

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

以下Binding:

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

从父级UserControl中我点击按钮设置值:

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

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

我期待我的DataGrid被更新,但是不是。你能否指出我在做错什么?

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

推荐答案

自动属性遗憾的是不支持更改通知。因此,如果您设置源代码 -Property,DataGrid将不知道该集合已被更改。

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.

一种可能性是为 messagesGrid.source INotifiyPropertyChanged 实现 -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");
            } 
        }
  } 
  ....

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

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> 

这篇关于在指定新值后将ObservableCollection绑定到DataGrid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆