c# – 带MVVM的WPF数据网格

栏目: ASP.NET · 发布时间: 6年前

内容简介:翻译自: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(如果它不会自动更新).

只需订阅ObservableCollection的CollectionChanged事件即可.事件处理程序接收 NotifyCollectionChangedEventArgs

类的实例,该实例包含一个属性“Action”,描述是否已添加或删除行.它还包含已添加的行(‘NewItems’)或已删除的行(‘OldItems’)的列表.这应该为您提供足够的信息来更新您的数据库.

您可以在ViewModel行中实现 INotifyPropertyChanged (我猜测类ItemsList),然后订阅它,以查明行是否脏,需要在数据库中更新.该接口由单个事件PropertyChanged组成,只要值发生更改,就会在ViewModel的属性设置器中引发该事件.

你是对的NotifyCollectionChanged事件来得太早,无法立即插入数据库.但是您可以在事件处理程序中将该行标记为“inserted”,并在完成该行所需的最后一个属性更改事件(参见上文)后立即插入该行.

翻译自:https://stackoverflow.com/questions/7007389/wpf-datagrid-with-mvvm


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Nature of Code

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》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

URL 编码/解码
URL 编码/解码

URL 编码/解码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具