首页 > 解决方案 > C# WPF DataGrid with user input and update the variables accordingly

问题描述

I have a DataGrid and class "MyNewEntry", and this class implement INotifyPropertyChanged, so every changes in the dictionary, will also affect the value shown in the datagrid.

See the codes below.

Dictionary<string, MyNewEntry> dicForMyNewEntrys = new Dictionary<string, MyNewEntry>();

ObservableCollection<MyNewEntry> entryRowMyNewEntrys = new ObservableCollection<MyNewEntry>();

myDataGrid.ItemsSource = entryRowMyNewEntrys;

And I wanted to update the dictionary according to the user inputs.

  1. when user add new rows

  2. when user delete rows from the datagrid

  3. when user edit some datagridcells

For Number 3 I can catch the event CellEditEnding (may be there is are better way to do it) but for the rest, I am not sure how to do it in a nice way.

标签: c#wpfdatagrid

解决方案


当您在 中编辑某个单元格时DataGrid,您实际上是在设置MyNewEntry类的相应属性。因此,如果您像这样创建源集合,字典中的值应该会自动更新:

ObservableCollection<MyNewEntry> entryRowMyNewEntrys = new ObservableCollection<MyNewEntry>(dicForMyNewEntrys.Values);

为了能够解决 1 和 2,您可以处理 的CollectionChanged事件ObservableCollection<MyNewEntry>,例如:

entryRowMyNewEntrys.CollectionChanged += (s, e) =>
{
    switch (e.Action)
    {
        case NotifyCollectionChangedAction.Add:
            MyNewEntry added = e.NewItems?.OfType<MyNewEntry>().FirstOrDefault();
            string key = "...";
            if (added != null && !dicForMyNewEntrys.ContainsKey(key))
                dicForMyNewEntrys.Add(key, added);
            break;
        case NotifyCollectionChangedAction.Remove:
            MyNewEntry removed = e.OldItems?.OfType<MyNewEntry>().FirstOrDefault();
            key = "...";
            if (removed != null && dicForMyNewEntrys.ContainsKey(key))
                dicForMyNewEntrys.Remove(key);
            break;
    }
};

推荐阅读