zoukankan      html  css  js  c++  java
  • WPF MVVM DataGrid数据直更新

    WPF MVVM所有类基本上都会实现System.ComponentModel.INotifyPropertyChanged接口 .举例为TestModel实体类A3只是A1与A2的数据处理后显示,只要A1或A2有更新的情况前台UI都有变化实体如下.

    但在DataGrid中有个很特别的问题,进入了编辑模式但在更新A1时退出当前单元的编辑模式,而不退出编辑行时A3的数据是不会有反应的变化.这样子有才生了一个问题,如果有好几个属性都是有关联的不可能为了知道属性处理真的变化,让客户换行后,发现数据不对了返回那个行进行编辑吧.这样也太友好了.那样实际下图的功能呢

    . 

    这样主是用到MVVM的Binding功能.而在控件的属性BindingGroup中反取回你在Binding时的相关属性,而这个类在MVVM中UI改变时返传到VM对应属性时就是由这类来可控制.这MVVM的机制说起来就很复杂了.还是直接上代码吧

    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;

    }

    }

    使用代码使用附加属性<DataGrid yy:DataGridHelper.RealTimeCommit="True">

  • 相关阅读:
    地区表设计(包括数据插入) Dear
    本博客的内容
    linux msn
    相关的一些技术
    相关的一些产品
    考第一名的学生的发言
    AIX&LINUX操作系统调优
    shell for循环
    自动化测试
    DB2数据库日志
  • 原文地址:https://www.cnblogs.com/DasonKwok/p/2657834.html
Copyright © 2011-2022 走看看