logo Devexpress WPF控件文档中心

第3课 - 向数据库发布更改


本教程演示了如何在GridControl中编辑数据并将更改保存到数据库中。本教程以第2课显示和编辑数据为基础。

1. 设置TableView.ShowUpdateRowButtons属性为OnCellEditorOpen或OnCellValueChange。这将开启一个编辑模式,允许用户编辑整个行,然后一次性提交或取消所有更改。

2. GridControl会将更改保存在本地,而不会将其发布到数据库中。要将更改保存到数据库,在ViewModel中创建一个ValidateAndSaveCommand。该命令调用数据上下文的SaveChanges方法。

ViewModel.cs

public class ViewModel : ViewModelBase {
    NorthwindEntities northwindDBContext;
    public ViewModel() {
        ...
        ValidateAndSaveCommand = new DelegateCommand(ValidateAndSave);
    }
    ...
    public DelegateCommand ValidateAndSaveCommand { get; }
    void ValidateAndSave() {
        northwindDBContext.SaveChanges();
    }
}

ViewModel.vb

Public Class ViewModel
    Inherits ViewModelBase

    Private northwindDBContext As NorthwindEntities

    Public Sub New()
        ValidateAndSaveCommand = New DelegateCommand(AddressOf ValidateAndSave)
    End Sub

    Public ReadOnly Property ValidateAndSaveCommand As DelegateCommand

    Private Sub ValidateAndSave()
        northwindDBContext.SaveChanges()
    End Sub
End Class
3. 将EventToCommand对象分配给View的Interaction.Behaviors集合,并将ValidateAndSaveCommand订阅给GridViewBase.ValidateRow事件。在用户点击更新按钮后,GridControl会引发该事件。

MainWindows.xaml

<dx:ThemedWindow
    ...
    xmlns:dxmvvm="http://schemas.devexpress.com/winfx/2008/xaml/mvvm">
    <dxg:TableView ShowUpdateRowButtons="OnCellEditorOpen" ...>
        <dxmvvm:Interaction.Behaviors>
            <dxmvvm:EventToCommand EventName="ValidateRow"
                                   Command="{Binding Path=ValidateAndSaveCommand}"/>
        </dxmvvm:Interaction.Behaviors>
    </dxg:TableView>


在线咨询
联系我们

客服热线
023-68661681

QQ客服

意见反馈


添加微信获专业服务

TOP