2010-01-16 530 views
1

這將是一個愚蠢的問題,但一個集合中有一個Datagridview和一個數據對象。 de datagridview的數據源被設置爲這個集合(類型BindingList)。Datagridview datacolumn不會更新(嵌套屬性)

當我更新屬性時,所有數據將被顯示並且datagrid中的一些數據也將更新。但僅限於數據對象的第一級。更改二級屬性(來自嵌套對象)不會使用新值自動刷新數據網格的datacolumn。

實施例:

class A 
{ 
    public string SampleField; 
    public B ClassB; 
} 
class B 
{ 
    public string FieldB; 
} 

當類B.FieldB由代碼updatet,在DataGridView不顯示變化。

我也嘗試過使用數據網格的CelLFormatting_Event,但它不會觸發事件。

另一種解決方案是調用BindingList.ResetBindings(),但在這種情況下,datagridview重新顯示所有不好看(你看到al行再次建設)。

所以,我的問題是,什麼是解決這個問題的最佳解決方案。

謝謝。

回答

1

DGV未更新,因爲您的代碼在值更改時未通知DGV。你需要在兩個類中實現INotifyPropertyChanged。爲此,您還需要將您的字段更改爲屬性:

class A : INotifyPropertyChanged 
{ 
    private string _sampleField; 
    public string SampleField 
    { 
     get { return _sampleField; } 
     set 
     { 
      _sampleField = value; 
      OnPropertyChanged("SampleField"); 
     } 
    }; 

    private B _classB 
    public B ClassB 
    { 
     get { return _classB; } 
     set 
     { 
      _classB = value; 
      OnPropertyChanged("ClassB"); 
     } 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 

    protected virtual void OnPropertyChanged(string propertyName) 
    { 
     PropertyChangedEventHander handler = PropertyChanged; 
     if (handler != null) 
      handler(this, new PropertyChangedEventArgs(propertyName); 
    } 
} 

class B : INotifyPropertyChanged 
{ 
    private string _fieldB; 
    public string FieldB 
    { 
     get { return _fieldB; } 
     set 
     { 
      _fieldB = value; 
      OnPropertyChanged("FieldB"); 
     } 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 

    protected virtual void OnPropertyChanged(string propertyName) 
    { 
     PropertyChangedEventHander handler = PropertyChanged; 
     if (handler != null) 
      handler(this, new PropertyChangedEventArgs(propertyName); 
    } 
}