在项目中碰到了这个问题,在网上搜了半天,发现了一种解决方案,这种方法主要是在DataGrid加载Row时设定Row的行号,主要代码如下:

LoadingRow
1 DataGrid.LoadingRow += (sender,e)=>
2 {
3   e.Row.Header = e.Row.GetIndex()+1;
4 };

但是在实际应用的过程中,发现一些问题,比如现在整个DataGrid的行都加载完了,现在DataGrid的行号是对的,但是,当从DataGrid中删除或是再增加一些行时,这时DataGrid的行号就显示错误了,主要原因的LoadingRow事件只是在Row加载时执行了一下,并没有在Row更新时再刷新行号,针对这个问题,我自己写了一段代码用来解决Row行号刷新的问题,由于DataGrid中并没有Rows这个属性,所以我们无法遍历DataGird的所有行对行号进行刷新(DataGrid的Row为DataGridRow类型,至少现在我还没发现怎么遍历,如果有发现的朋友可以指点指点),好吧,贴代码:

View Code
 1 publicstaticclass DataGridRowHelper
2 {
3 #region ShowRowIndex
4 publicstaticreadonly DependencyProperty ShowRowIndexProperty = DependencyProperty.RegisterAttached("ShowRowIndex", typeof(bool), typeof(DataGridRowHelper), new PropertyMetadata(false, new PropertyChangedCallback(OnShowRowIndexPropertyChanged)));
5 privatestaticvoid OnShowRowIndexPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
6 {
7 if (sender is DataGrid)
8 {
9 DataGrid _dataGrid = sender as DataGrid;
10 _dataGrid.LoadingRow -= _dataGrid_LoadingRow;
11 _dataGrid.UnloadingRow -= _dataGrid_UnloadingRow;
12 bool newValue = (bool)e.NewValue;
13 if (newValue)
14 {
15 _dataGrid.LoadingRow += _dataGrid_LoadingRow;
16 _dataGrid.UnloadingRow += _dataGrid_UnloadingRow;
17 }
18 }
19 }
20 staticvoid _dataGrid_UnloadingRow(object sender, DataGridRowEventArgs e)
21 {
22 List<DataGridRow> rows = GetRowsProperty(sender as DataGrid);
23 if (rows.Contains(e.Row))
24 rows.Remove(e.Row);
25 foreach (DataGridRow row in rows)
26 row.Header = row.GetIndex() +1;
27 }
28 staticvoid _dataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
29 {
30 List<DataGridRow> rows = GetRowsProperty(sender as DataGrid);
31 if (!rows.Contains(e.Row))
32 rows.Add(e.Row);
33 foreach (DataGridRow row in rows)
34 row.Header = row.GetIndex() +1;
35 }
36 publicstaticbool GetShowRowIndexProperty(DependencyObject obj)
37 {
38 return (bool)obj.GetValue(ShowRowIndexProperty);
39 }
40 publicstaticvoid SetShowRowIndexProperty(DependencyObject obj, bool value)
41 {
42 obj.SetValue(ShowRowIndexProperty, value);
43 }
44 #endregion
45
46 #region Rows
47 publicstaticreadonly DependencyProperty RowsProperty = DependencyProperty.RegisterAttached("Rows", typeof(List<DataGridRow>), typeof(DataGridRowHelper), new PropertyMetadata(new List<DataGridRow>()));
48
49 privatestatic List<DataGridRow> GetRowsProperty(DependencyObject obj)
50 {
51 return (List<DataGridRow>)obj.GetValue(RowsProperty);
52 }
53 #endregion
54 }

自己写了一个类,其中有个ShowRowIndex的附加属性,用于DataGrid类型,还有一个Rows的附加属性,私有只读,类型为List<DataGridRow>,用于存贮DataGird的所有行,这样的话可以在DataGrid每次加载或卸载时都对DataGrid的行号进行更新。用法很简单,如下所示:

用法
1 DataGridRowHelper.SetShowRowIndexProperty(NameOfDataGrid, true);

如果有朋友还有更加好的方法,欢迎交流!

posted on 2011-09-05 09:14  _无所事事_  阅读(1962)  评论(5编辑  收藏  举报