您的位置:首页 > 编程语言 > C#

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

2015-10-26 20:33 513 查看
    这些天一直在研究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为控件名称
 
  更新问题便解决了!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: