C# WPF数据绑定:更新ObservableCollection中的项

C# WPF数据绑定:更新ObservableCollection中的项,c#,wpf,data-binding,observablecollection,C#,Wpf,Data Binding,Observablecollection,我试图在WPF数据网格中反映ObservableCollection的更改。对列表的添加和删除效果很好,但我仍停留在编辑上 我在构造函数中初始化ObservableCollection: public MainWindow() { this.InitializeComponent(); this.itemList = new ObservableCollection<Item>(); DataGrid.ItemsSource = this.itemList;

我试图在WPF数据网格中反映ObservableCollection的更改。对列表的添加和删除效果很好,但我仍停留在编辑上

我在构造函数中初始化ObservableCollection:

public MainWindow()
{
    this.InitializeComponent();

    this.itemList = new ObservableCollection<Item>();
    DataGrid.ItemsSource = this.itemList;
    DataGrid.DataContext = this.itemList;
}
ObservableCollection的新增功能非常好:

Application.Current.Dispatcher.Invoke((Action) (() => this.itemList.Add(new Item { FirstName = firstName })));
TL;DR

我的问题是,如何在允许数据绑定更新GridView的同时更新列表中的项目

我未能实现这一目标,除非可耻地删除并重新添加该项目:

item.FirstName = newFirstName;
Application.Current.Dispatcher.Invoke((Action)(() => this.itemList.Remove(item)));
Application.Current.Dispatcher.Invoke((Action)(() => this.itemList.Add(item)));
更新

根据评论请求,以下是有关我如何进行更新的更多代码:

foreach (var thisItem in this.itemList)
{
    var item = thisItem;

    if (string.IsNullOrEmpty(item.FirstName))
    {
        continue;
    }

    var newFirstName = "Joe";

    item.FirstName = newFirstName; // If I stop here, the collection updates but not the UI. Updating the UI happens with the below calls.

    Application.Current.Dispatcher.Invoke((Action)(() => this.itemList.Remove(item)));
    Application.Current.Dispatcher.Invoke((Action)(() => this.itemList.Add(item)));

    break;
}

您的
对象中的
INotifyPropertyChanged
的实现未完成。实际上,
FirstName
属性没有更改通知。
FirstName
属性应为:

private string _firstName;
public string FirstName 
{ 
    get{return _firstName;}
    set
    {
        if (_firstName == value) return;
        _firstName = value;
        OnPropertyChanged("FirstName");
    }
}

显示更新是如何完成的我附加了一个代码示例,其中包含有关更新的更多信息。触摸属性命名。为了平息我自己的困惑,我只是更新了我的示例并重命名了属性
FirstName
。不是touché,只是在web编辑器中编写了这个,所以没有验证。试着用眼睛验证,我看到的只是_valueValue _valueValue。没什么大不了的,只是搞笑而已(笑脸就是这样)。使用VS/R#验证根本不是问题。效果很好!我希望你不介意,我编辑了你的答案以匹配我对问题所做的更改<代码>值把我弄糊涂了!伟大的我已批准编辑并删除了有关命名的评论(
private string _firstName;
public string FirstName 
{ 
    get{return _firstName;}
    set
    {
        if (_firstName == value) return;
        _firstName = value;
        OnPropertyChanged("FirstName");
    }
}