除非重新定义行中的所有项目,否则ObservableCollection不会更新到DataGrid行

时间:2019-07-15 13:58:33

标签: c# wpf

我将此结构的ObservableCollection TableRows绑定到DataGrid:

public class TableStruct
{
    public string Item1 {get; set;}
    public string Item2 {get; set;}
    public string Item3 {get; set;}
    public string Item4 {get; set;}
    public string Item5 {get; set;}
    public string Item6 {get; set;}
}

当尝试连续更新单个项目时,我尝试这样做:

for(int i = 0; i < TableRows.Count; i++)
{
    if(SomeConditional)
    {
        TableStruct new_row = TableRows[i];
        new_row.Item3 = "changed";
        TableRows[i] = new_row;
    }
}

但是在运行程序时,不会更新DataGrid。但是,运行此代码确实会更新到DataGrid并按预期工作:

for(int i = 0; i < TableRows.Count; i++)
{
    if(SomeConditional)
    {
        TableStruct new_row = new TableStruct();
        new_row.Item1 = "same";
        new_row.Item2 = "same";
        new_row.Item3 = "changed";
        new_row.Item4 = "same";
        new_row.Item5 = "same";
        new_row.Item6 = "same";
        TableRows[i] = new_row;
    }
}

这里有什么不同?在我看来,他们俩都完成了相同的任务,但是其中一个要比另一个多。

1 个答案:

答案 0 :(得分:0)

TableStruct应该实现INotifyPropertyChanged

public class TableStruct : INotifyPropertyChanged
{
    private string _item3;
    public string Item3
    {
        get { return _item3; }
        set { _item3 = value; NotifyPropertyChanged(); }
    }

    public event PropertyChangedEventHandler PropertyChanged;  
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    //...
}

如果通过在所有设置方法中调用PropertyChanged方法引发NotifyPropertyChanged()事件,则可以直接设置TableStruct的属性来更新UI:

for (int i = 0; i<TableRows.Count; i++)
{
    if (SomeConditional)
    {
        TableRows[i].Item3 = "changed";
    }
}

当项目的属性更改时,ObservableCollection<T>不会通知UI。它仅通知有关在集合中添加,删除或移动项目的信息。