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。

相关推荐
小小-猿几秒前
用 Python 写昇腾算子:pyasc 是怎么回事
开发语言·python·昇腾·cann·pyasc
涛涛ing2 分钟前
别再用 AI 写计算逻辑了:你的页面卡死,连鼠标都点不动
前端
星夜离尘563 分钟前
MATLAB:标定表局部倒退,为什么不能排序?
android·开发语言·matlab
智购科技智能售货柜7 分钟前
自动售货机步进电机细分驱动实战:力矩、噪声与堵转~YH
大数据·开发语言·人工智能·科技·嵌入式硬件
杜 硕1 小时前
从零开始的C++生活——第十五讲
开发语言·数据结构·c++·生活
OpenTiny社区1 小时前
当 AI 开始写 UI,我们缺的不是模型,是"设计词汇"
前端·github·ai编程
sunly_1 小时前
Go 切片详解
开发语言·oracle·golang
fengkai45451 小时前
Python对接LangChain智能体开发(Tool工具调用与 Agent智能体)
运维·开发语言·python·langchain·llm·ai agent·tool
随流寻影2 小时前
利用 C++ 实现二叉搜索树的增删查
开发语言·c++
Amos_Web2 小时前
Rspack 源码解析(三十八):SubresourceIntegrityPlugin 如何跨四个插件协作生成 integrity
前端