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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM