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">

  • 相关阅读:
    1230: [Usaco2008 Nov]lites 开关灯
    1821: [JSOI2010]Group 部落划分 Group
    1819: [JSOI]Word Query电子字典
    1820: [JSOI2010]Express Service 快递服务
    3038: 上帝造题的七分钟2
    1854: [Scoi2010]游戏
    Codevs3278[NOIP2013]货车运输
    关于使用lazytag的线段树两种查询方式的比较研究
    算法模板——splay区间反转 1
    3223: Tyvj 1729 文艺平衡树
  • 原文地址:https://www.cnblogs.com/DasonKwok/p/2657834.html
Copyright © 2011-2022 走看看