内容简介:翻译自:https://stackoverflow.com/questions/7007389/wpf-datagrid-with-mvvm
我正在尝试将WPF中的数据网格绑定到我的ViewModel,以便它将更新对数据库的任何单元格更改,并允许用户删除行并添加新行.我有部分工作,但无法找到ADD的ELEGANT解决方案并进行修改.
这是xaml
<DataGrid AutoGenerateColumns="false" HorizontalAlignment="Left" Margin="26,41,0,0" Name="dataGrid1" ItemsSource="{Binding Path=GetAllItems}" Height="200" VerticalAlignment="Top" Width="266" > <DataGrid.Columns> <DataGridTextColumn Binding="{Binding Path=ItemListID}" Header="ID" Visibility="Hidden"/> <DataGridTextColumn Binding="{Binding Path=ItemName}" Header="Name" Width="4*" /> <DataGridCheckBoxColumn Binding="{Binding Path=IsActive}" Header="Active" Width="*" /> </DataGrid.Columns>
然后在我的视图模型方法中
private ObservableCollection< ItemsList> getAllItems() { using (var context = new InspectorGeneralEntities()) { var query = from I in context.ItemsLists select I; var item = new ObservableCollection<ItemsList>(query.ToList()); return item; } }
删除行或修改数据网格上的行不会流入数据库.
a)我需要在xaml代码中创建哪些其他绑定来检测这些事件
b)如何在视图模型中检测已删除的记录或已修改的项目,以便我可以更新datacontext(如果它不会自动更新).
类的实例,该实例包含一个属性“Action”,描述是否已添加或删除行.它还包含已添加的行(‘NewItems’)或已删除的行(‘OldItems’)的列表.这应该为您提供足够的信息来更新您的数据库.
您可以在ViewModel行中实现 INotifyPropertyChanged (我猜测类ItemsList),然后订阅它,以查明行是否脏,需要在数据库中更新.该接口由单个事件PropertyChanged组成,只要值发生更改,就会在ViewModel的属性设置器中引发该事件.
你是对的NotifyCollectionChanged事件来得太早,无法立即插入数据库.但是您可以在事件处理程序中将该行标记为“inserted”,并在完成该行所需的最后一个属性更改事件(参见上文)后立即插入该行.
翻译自:https://stackoverflow.com/questions/7007389/wpf-datagrid-with-mvvm
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- 分布式数据网格 Data Mesh
- 融数链(FBT)网格化多维数据价值交换生态
- 数据包在 Istio 网格中的生命周期
- 微服务中如何设计高扩展、易维护的“数据网格”?
- Redisson 3.12.3 发布,基于 Redis 的 Java 驻内存数据网格
- Redisson 3.7.0 、2.12.0 发布,Redis Java 驻内存数据网格
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
The Nature of Code
Daniel Shiffman / The Nature of Code / 2012-12-13 / GBP 19.95
How can we capture the unpredictable evolutionary and emergent properties of nature in software? How can understanding the mathematical principles behind our physical world help us to create digital w......一起来看看 《The Nature of Code》 这本书的介绍吧!