數據綁定
WPF之DataGrid應用
WPF 4 DataGrid 控件(基本功能篇)silverlight中ItemsSource和DataContext的用法注意
ItemsSource 通常是一個集合或列表元素,用來設置DataGrid等如何顯示元素,無法讓其子元素繼承使用
DataContext,數據上下文用來設置DataGrid的數據源,數據源可以是集合或屬性或其他元素。在Silverlight中某個父級元素設置了DataContext,其子元素將可以繼承並且使用DataContext中的屬性。
1.在XAML中設置DataGrid的ItemsSource={Binding xx}
2.codebehind中通過dataGrid.DataContext = List<class>來設置DataContext。
WPF_DataGrid_ItemsSource綁定
應用 WPF DataGrid ItemsSource 綁定的時候,遇到幾個問題:
1. 報錯:此視圖不允許“EditItem”。
2. 綁定了 List<string> 到 ItemsSource 但是 List<string> 變化的時候,ItemsSource 不發生變化。
解決方法:
1. 現測是因爲 ItemsSource 沒有綁定,無法定位視圖?因爲我綁定了ItemsSource 以後就沒有這個問題了,可以編輯了。
2. 使用 ObservableCollection<string>,因爲 List<string> 沒有實現 INotifyCollectionChanged 接口,這個接口會定義一個事件,這個事件會通知上層,添加或者刪除的時候會觸發。ObservableCollection 默認實現這個接口,使用方法和 List 一樣,當然也可以自己寫個類,實現 INotifyCollectionChanged 接口。
WPF DataGrid實現爲某個單元格賦值、獲取某列的和、積等
一、DataGrid實現爲某個單元格賦值
在WPF中,要對DataGrid的某個單元格進行賦值。一般不便直接對DataGrid賦值。而是對其綁定的數據源進行賦值。
現在假定有: dt_Common 爲DataTable類型,dataGrid_CommonSeat爲某個DataGrid.可以通過以下方式綁定:
//綁定普通坐席數據 dt_Common = (DataTable)DBHelper.ExecSql(sql_Common, conStr, DBHelper.OperateType.Select); dataGrid_CommonSeat.ItemsSource = dt_Common.DefaultView;
現在要對其中的某些單元格進行賦值。則可以通過對齊綁定的數據源dt_Common 進行賦值來實現。
string price = dt_Common.Rows[dataGrid_CommonSeat.SelectedIndex][1].ToString(); string count = dt_Common.Rows[dataGrid_CommonSeat.SelectedIndex][2].ToString(); if (string.IsNullOrEmpty(price) || string.IsNullOrEmpty(count)) return; double d = double.Parse(price) * double.Parse(count); dt_Common.Rows[dataGrid_CommonSeat.SelectedIndex][4] = d;
這樣,就對dataGrid_CommonSeat的當前行第4列的單元格內容賦值成功了。
二、獲取DataGrid某列的和、積等
這個很簡單,遍歷、判斷不爲空則相加或想減相乘即可。下面是封裝的一個方法。改改就可以自己用了。
/// <summary> /// 獲取DataGrid中第index列的值的和 /// </summary> /// <param name="datagrid">宿主DataGrid</param> /// <param name="index">列下標.</param> /// <returns></returns> /// <Author> frd 2011-9-20 20:03</Author> public static double GetDataGridColumnSum(DataGrid datagrid, int index) { double result = 0; double temp = 0; for (int i = 0; i < datagrid.Items.Count; i++) { DataRowView mySelectedElement = datagrid.Items[i] as DataRowView; if (mySelectedElement == null) continue; double.TryParse(mySelectedElement.Row.ItemArray[index].ToString(), out temp); result += temp; } return result; }