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

  • 相关阅读:
    HYSBZ 3813 奇数国
    HYSBZ 4419 发微博
    HYSBZ 1079 着色方案
    HYSBZ 3506 排序机械臂
    HYSBZ 3224 Tyvj 1728 普通平衡树
    Unity 3D,地形属性
    nginx 的naginx 种包含include关键字
    Redis 出现NOAUTH Authentication required解决方案
    mysql 8.0出现 Public Key Retrieval is not allowed
    修改jar包里的源码时候需要注意的问题
  • 原文地址:https://www.cnblogs.com/DasonKwok/p/2657834.html
Copyright © 2011-2022 走看看