WPF 根据坐标获取控件DataContext的例子

cs 复制代码
private string GetSelectedCellContent(DataGrid grid, Point position)

{

    position = grid.PointFromScreen(position);

    var hit = VisualTreeHelper.HitTest(grid, position);

    if (hit == null)

        return null;

    var cell = hit.VisualHit.GetParent<DataGridCell>();

    if (cell == null)

        return null;

    return cell.DataContext.GetType()

        .GetProperty(cell.Column.Header.ToString(), BindingFlags.Instance | BindingFlags.Public)

        .GetValue(cell.DataContext).ToString();

}

这段代码是一个私有方法,用于获取指定位置在DataGrid控件中对应的单元格的内容。它接受两个参数:一个DataGrid控件和一个Point对象,

表示在屏幕上的位置。以下是代码的详细解释:

  1. `position = grid.PointFromScreen(position);`:将屏幕坐标转换为相对于DataGrid控件的坐标。

  2. `var hit = VisualTreeHelper.HitTest(grid, position);`:使用VisualTreeHelper的HitTest方法,在DataGrid控件中查找指定位置下的元素。

  3. `if (hit == null) return null;`:如果HitTest方法没有找到任何元素,则返回null。

  4. `var cell = hit.VisualHit.GetParent<DataGridCell>();`:从HitTest方法返回的元素开始,向上遍历Visual树,直到找到DataGridCell元素。

  5. `if (cell == null) return null;`:如果找不到DataGridCell元素,则返回null。

  6. `return cell.DataContext.GetType().GetProperty(cell.Column.Header.ToString(), BindingFlags.Instance | BindingFlags.Public).GetValue(cell.DataContext).ToString();`

:获取DataGridCell的DataContext对象的类型,然后使用反射获取DataContext对象中与DataGridCell的列标题对应的属性的值,并将其转换为字符串返回。

这段代码的主要作用是获取指定位置在DataGrid控件中对应的单元格的内容。它首先将屏幕坐标转换为相对于DataGrid控件的坐标,然后使用VisualTreeHelper的HitTest方法查找指定位置下的元素。如果找到了DataGridCell元素,则使用反射获取DataContext对象中与DataGridCell的列标题对应的属性的值,并将其转换为字符串返回。如果找不到DataGridCell元素,则返回null。

相关推荐
萑澈5 小时前
Windows 7 运行 Electron 安装包报“不是有效的 Win32 应用程序”怎么办
javascript·windows·electron
W.A委员会5 小时前
JS原型链详解
开发语言·javascript·原型模式
止语Lab5 小时前
Go并发编程实战:Channel 还是 Mutex?一个场景驱动的选择框架
开发语言·后端·golang
懂懂tty5 小时前
React状态更新流程
前端·react.js
小码哥_常6 小时前
告别繁琐!手把手教你封装超实用Android原生Adapter基类
前端
她说彩礼65万6 小时前
C# 实现简单的日志打印
开发语言·javascript·c#
绿浪19846 小时前
c# 中结构体 的定义字符串字段(性能优化)
开发语言·c#
skywalk81636 小时前
pytest测试的时候这是什么意思?Migrating <class ‘kotti.resources.File‘>
前端·python
房开民6 小时前
可变参数模板
java·开发语言·算法
一只蝉nahc6 小时前
vue使用iframe内嵌unity模型,并且向模型传递信息,接受信息
前端·vue.js·unity