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。

相关推荐
云和数据.ChenGuang9 分钟前
python sorted函数详细剖析
开发语言·人工智能·windows·python·1024程序员节
外收内放15 分钟前
FastAPI猜字谜实战(4):让AI主持人开口
开发语言·python·学习·fastapi
云和数据.ChenGuang15 分钟前
Python map() 函数详解:从语法、原理到实战用法
开发语言·人工智能·python·langchain·1024程序员节
秋名RG18 分钟前
(二)存储、CPU 与指令执行——程序为什么快,又为什么慢
java·开发语言
Highcharts.js21 分钟前
Highcharts甘特图开发带导航功能的项目管理图示例
开发语言·前端·javascript·甘特图·highcharts·项目管理图
kyle~22 分钟前
C++ 原子操作、内存模型与无锁并发编程
linux·开发语言·c++·操作系统
BeiGuTing_code25 分钟前
Java泛型与Object
java·开发语言
2401_8724187829 分钟前
互联网公开信息检索完全指南:Google、Yandex、Wayback Machine、DNS、WHOIS、Shodan 等 OSINT 工具大全
开发语言·php
HEJOO931 分钟前
Java 类加载过程详解:从加载到初始化的完整链路
java·开发语言·firefox
hahaha601639 分钟前
数字图像锐化
开发语言·python