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。

相关推荐
Cicada1284 分钟前
Web 服务器怎么选
运维·服务器·前端
Patrick在香港5 分钟前
Claude + Python 数据管道:一次字段改名,786 行历史数据被静默重写
开发语言·windows·python·claude·数据工程·数据校验·数据管道
不可能片场5 分钟前
接口返回 200 不代表活着:catch-all 路由的陷阱
前端·electron
farerboy10 分钟前
编程技巧:VUE 实现接口返回数据的流式处理
javascript·vue.js
用户9210802628611 分钟前
Cookie 和 Token,到底谁在负责登录态
前端
阳火锅12 分钟前
2025,记住这一年!它是古法编程的最后一年。
前端·javascript·面试
sibylyue14 分钟前
【报表和BI大屏】ECharts数据可视化大屏 / 驾驶舱
前端·信息可视化·echarts
用户9210802628619 分钟前
为什么 Header 是 HTTP 的灵魂
前端
特立独行的猫A21 分钟前
AtomMQTT Broker — 用 Rust 实现的轻量级高性能 MQTT 消息代理
前端·后端·架构
CodeStats22 分钟前
【Java数据类型】Java底层数据类型原理(下):时间API、JSON与String存储演进
java·开发语言·数据类型·string·byte