c# - 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.
when user add new rows
when user delete rows from the datagrid
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.
解决方案
当您在 中编辑某个单元格时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;
}
};
推荐阅读
- javascript - 如何确定请求者是我的 Web 应用程序
- javascript - 如何在页面刷新时将用户的位置存储在相同的滚动位置
- node.js - 路由在 src/index.html 角度不起作用
- asp.net-core - Shieldui - ASP.Net Core CRUD 操作 - 弹出编辑
- regex - Notepad++ 书签行包含特定字符并使用正则表达式从字符串中间开始
- android - 为什么gradlew assembleDebug不运行jetifier,而react-native run-android运行jetifier?
- jquery - 如何删除 jQuery 数据表中的隐藏复选框
- python - 在Python中检查目录是否为空的最快方法是什么
- android - 如果他们在android中没有jsonobject,如何从Jsonarray获取Jsonarray
- vue.js - vue 多次发出一次