1 /* ----------------------------------------------------------
2 文件名称:DataGridPlus.cs
3
4 作者:秦建辉
5
6 MSN:[email protected]
7 QQ:36748897
8
9 博客:http://blog.csdn.net/jhqin
10
11 开发环境:
12 Visual Studio V2010
13 .NET Framework 4 Client Profile
14
15 版本历史:
16 V1.0 2012年06月07日
17 WPF DataGrid控件扩展方法
18
19 参考资料:
20 http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/b7299e55-92e2-4a6b-8987-869fef8f22eb/
21 ------------------------------------------------------------ */
22 using System.Windows.Controls;
23 using System.Windows.Controls.Primitives;
24 using System.Windows.Media;
25
26 namespace Splash.WPF
27 {
28 public static class DataGridPlus
29 {
30 /// <summary>
31 /// 获取DataGrid控件单元格
32 /// </summary>
33 /// <param name="dataGrid">DataGrid控件</param>
34 /// <param name="rowIndex">单元格所在的行号</param>
35 /// <param name="columnIndex">单元格所在的列号</param>
36 /// <returns>指定的单元格</returns>
37 public static DataGridCell GetCell(this DataGrid dataGrid, int rowIndex, int columnIndex)
38 {
39 DataGridRow rowContainer = dataGrid.GetRow(rowIndex);
40 if (rowContainer != null)
41 {
42 DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);
43 DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);
44 if (cell == null)
45 {
46 dataGrid.ScrollIntoView(rowContainer, dataGrid.Columns[columnIndex]);
47 cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);
48 }
49 return cell;
50 }
51 return null;
52 }
53
54 /// <summary>
55 /// 获取DataGrid的行
56 /// </summary>
57 /// <param name="dataGrid">DataGrid控件</param>
58 /// <param name="rowIndex">DataGrid行号</param>
59 /// <returns>指定的行号</returns>
60 public static DataGridRow GetRow(this DataGrid dataGrid, int rowIndex)
61 {
62 DataGridRow rowContainer = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex);
63 if (rowContainer == null)
64 {
65 dataGrid.UpdateLayout();
66 dataGrid.ScrollIntoView(dataGrid.Items[rowIndex]);
67 rowContainer = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex);
68 }
69 return rowContainer;
70 }
71
72 /// <summary>
73 /// 获取父可视对象中第一个指定类型的子可视对象
74 /// </summary>
75 /// <typeparam name="T">可视对象类型</typeparam>
76 /// <param name="parent">父可视对象</param>
77 /// <returns>第一个指定类型的子可视对象</returns>
78 public static T GetVisualChild<T>(Visual parent) where T : Visual
79 {
80 T child = default(T);
81 int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
82 for (int i = 0; i < numVisuals; i++)
83 {
84 Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
85 child = v as T;
86 if (child == null)
87 {
88 child = GetVisualChild<T>(v);
89 }
90 if (child != null)
91 {
92 break;
93 }
94 }
95 return child;
96 }
97 }
98 }
以上只是个人想法和实践经验所得,如果有文字错误和语法错误,请加以指点!
QQ:247039968
emil:[email protected]
无论是美女的歌声,还是鬣狗的狂吠,无论是鳄鱼的眼泪,还是恶狼的嚎叫,都不会使我动摇