简体   繁体   中英

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.

When you edit some cell in the DataGrid , you are actually setting the corresponding property of the MyNewEntry class. So if you create the source collection like this, the values in the dictionary should be updated automatically:

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

To be able to solve 1 and 2, you could handle the CollectionChanged event of the ObservableCollection<MyNewEntry> , eg:

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;
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM