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



我正试图在WPF数据网格中反映ObservableCollection的更改。在列表中添加和删除操作都很好,但我一直在编辑。

我在构造函数中初始化ObservableCollection

public MainWindow()
{
    this.InitializeComponent();
    this.itemList = new ObservableCollection<Item>();
    DataGrid.ItemsSource = this.itemList;
    DataGrid.DataContext = this.itemList;
}

我有一个实现INotifyPropertyChanged:的类

public class Item : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    public string FirstName { get; set; }
    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var handler = this.PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

添加到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;
}

INotifyPropertyChangedItem对象中的实现不完整。实际上,FirstName属性没有更改通知。FirstName属性应为:

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

最新更新