WPF 获得DataGridRow和 DataGridCell的方法
2015-10-30 12:29
363 查看
原文地址
因此我们需要自己来编写获取的方法,这其中主要用到了ItemsControl类的一个实例方法:ItemContainerGenerator。
简介
在WPF中,DataGrid控件并没有提供访问其DataGridRow或者DataGridCell的方法。因此我们需要自己来编写获取的方法,这其中主要用到了ItemsControl类的一个实例方法:ItemContainerGenerator。
实现代码
using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Media; namespace Splash.WPF { public static class DataGridPlus { /// <summary> /// 获取DataGrid控件单元格 /// </summary> /// <param name="dataGrid">DataGrid控件</param> /// <param name="rowIndex">单元格所在的行号</param> /// <param name="columnIndex">单元格所在的列号</param> /// <returns>指定的单元格</returns> public static DataGridCell GetCell(this DataGrid dataGrid, int rowIndex, int columnIndex) { DataGridRow rowContainer = dataGrid.GetRow(rowIndex); if (rowContainer != null) { DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer); DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex); if (cell == null) { dataGrid.ScrollIntoView(rowContainer, dataGrid.Columns[columnIndex]); cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex); } return cell; } return null; } /// <summary> /// 获取DataGrid的行 /// </summary> /// <param name="dataGrid">DataGrid控件</param> /// <param name="rowIndex">DataGrid行号</param> /// <returns>指定的行号</returns> public static DataGridRow GetRow(this DataGrid dataGrid, int rowIndex) { DataGridRow rowContainer = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex); if (rowContainer == null) { dataGrid.UpdateLayout(); dataGrid.ScrollIntoView(dataGrid.Items[rowIndex]); rowContainer = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex); } return rowContainer; } /// <summary> /// 获取父可视对象中第一个指定类型的子可视对象 /// </summary> /// <typeparam name="T">可视对象类型</typeparam> /// <param name="parent">父可视对象</param> /// <returns>第一个指定类型的子可视对象</returns> public static T GetVisualChild<T>(Visual parent) where T : Visual { T child = default(T); int numVisuals = VisualTreeHelper.GetChildrenCount(parent); for (int i = 0; i < numVisuals; i++) { Visual v = (Visual)VisualTreeHelper.GetChild(parent, i); child = v as T; if (child == null) { child = GetVisualChild<T>(v); } if (child != null) { break; } } return child; } } }
相关文章推荐
- 【转】互联网时代的关键人物:大公司的小领导
- Python - MySQLdb
- Cocos2d 2.x 运动中的速度效果
- 【Quick 3.3】资源脚本加密及热更新(二)资源加密
- 解决DDMS无法查看/data目录问题
- I2C 协议
- Java 单例模式 SingletTon
- angularJs-HelloWorld
- Android编程使WebView支持HTML5 Video全屏播放的解决方法
- 帝国cms在任意位置调用指定id的栏目名称和链接
- 每天一个linux命令(26):用SecureCRT来上传和下载文件
- Git常用命令速查02 - 本地修改
- 开始做超级拆工,给android程序加注释
- Socket-TCP-1
- shell杂记
- js压缩图片(ajax上传)
- shell杂记
- ANR异常的产生和解决方案
- HDU 3068 最长回文(manacher算法模板)
- ASM在游戏服务器的使用