C# WPF DataGrid控件同行编辑的实时更新问题

    这些天一直在研究WPF,试图用其来进行数据库客户端的制作。DataGrid控件以其数据显示和实时编辑的方便易用,自然是不能不用。

    数据库程序中,往往要实现多级联动这一功能以实现范围的选择等。本人在实现该功能的过程中发现DataGrid控件一个让人十分崩溃的点,就是在编辑完一个单元格的数据之后,需要将焦点移动到下一行或者别的控件后,刚刚编辑完的数据才会被更新到绑定的数据对象中。而如果编辑完一个单元格数据后将焦点移动到其同一行的其他单元格,则刚刚编辑完的数据没有及时更新(这跟INotifyPropertyChanged接口的实现无关,也跟绑定的方式无关)。这就很容易导致程序出错,比如使用DataGrid的模板做“省\市\区”的三级联动下拉列表,当省的选择发生改变时,市还是发生改变前的那些选项,这就跪了。

    在各种百度差点就去翻墙GOOGLE之际,看到了这篇文章,问题就解决!善哉善哉,愿好人一生平安,祝好人长命百岁。

    由于本人刚刚学WPF,该文章谈的一些原理性的东西本人还不太明了,就只贴出解决过程,有需要的可以去上面提到的那篇博客中跟博主交流或者等本人日后了然了些来更新这篇博客的原理部分。

    一.添加一个新类,叫做DataGridHelper,会使用到如下的命名空间:

using System.Windows;
using System.Windows.Controls;
    类的声明如下:
public static class DataGridHelper
{
    public static void SetRealTimeCommit(DataGrid dataGrid, bool isRealTime)
    {
        dataGrid.SetValue(RealTimeCommitProperty, isRealTime);
    }

    public static bool GetRealTimeCommit(DataGrid dataGrid)
    {
        return (bool)dataGrid.GetValue(RealTimeCommitProperty);
    }

    public static readonly DependencyProperty RealTimeCommitProperty =
    DependencyProperty.RegisterAttached("RealTimeCommit", typeof(bool),
    typeof(DataGridHelper),
    new PropertyMetadata(false, RealTimeCommitCallBack));

    private static void RealTimeCommitCallBack(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var dg = d as DataGrid;
        if (dg == null)
            return;
        EventHandler<DataGridCellEditEndingEventArgs> ceHandler = delegate (object xx, DataGridCellEditEndingEventArgs yy)
        {
            var flag = GetRealTimeCommit(dg);
            if (!flag)
                return;
            var cellContent = yy.Column.GetCellContent(yy.Row);
            if (cellContent != null && cellContent.BindingGroup != null)
                cellContent.BindingGroup.CommitEdit();
        };
        dg.CellEditEnding += ceHandler;
        RoutedEventHandler eh = null;
        eh = (xx, yy) =>
        {
            dg.Unloaded -= eh;
            dg.CellEditEnding -= ceHandler;
        };
        dg.Unloaded += eh;
    }
}
    二.在希望控件更新数据的时候,使用如下代码:
DataGridHelper.SetRealTimeCommit(dataGrid, true);//dataGrid为控件名称
    更新问题便解决了!




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值