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。

相关推荐
小林望北6 分钟前
Kotlin 协程:StateFlow 与 SharedFlow 深度解析
android·开发语言·kotlin
盐烟6 分钟前
xpath-csv_doban_slider
开发语言·python
小学生-山海7 分钟前
【安卓逆向】WE Learn登录接口iv、pwd参数分析,加密逆向分析
开发语言·python·安卓逆向
Slow菜鸟7 分钟前
Java 开发环境安装指南(7) | Nginx 安装
java·开发语言·nginx
沐苏瑶8 分钟前
Java反序列化漏洞
java·开发语言·网络安全
进击的荆棘8 分钟前
C++起始之路——用哈希表封装myunordered_set和myunordered_map
开发语言·c++·stl·哈希算法·散列表·unordered_map·unordered_set
心.c10 分钟前
大厂高频手写题
开发语言·前端·javascript
guslegend12 分钟前
AI生图第2节:python对接gpt-image-2模型API生图
开发语言·python·gpt
原来是猿1 小时前
Linux线程同步与互斥(四):日志系统与策略模式
linux·运维·开发语言·策略模式
zhensherlock2 小时前
Protocol Launcher 系列:Working Copy 文件操作与高级命令详解
javascript·git·typescript·node.js·自动化·github·js