You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过代码获取WPF DataGridTemplateColumn列头的ToolTip

获取DataGridTemplateColumn Header中ToolTip的内容

嘿,我来帮你搞定这个问题!既然你是把ToolTip直接绑定在Header里的TextBlock上,那核心思路就是先拿到这个TextBlock实例,再读取它的ToolTip属性值就好啦。

步骤1:定位目标DataGridTemplateColumn

首先你需要找到对应的列,假设你的DataGrid控件名为myDataGrid,可以用LINQ来筛选:

// 筛选出Header的TextBlock文本为"Current"的DataGridTemplateColumn
var targetColumn = myDataGrid.Columns
    .FirstOrDefault(col => col is DataGridTemplateColumn 
        && col.Header is TextBlock tb 
        && tb.Text == "Current") as DataGridTemplateColumn;

步骤2:获取ToolTip内容

一旦找到目标列,就可以把Header转型为TextBlock,然后读取ToolTip:

if (targetColumn != null && targetColumn.Header is TextBlock headerTextBlock)
{
    // 因为你设置的ToolTip是字符串"Price",可以直接强转
    if (headerTextBlock.ToolTip is string toolTipText)
    {
        // 这里toolTipText就是你要的"Price"
        Debug.WriteLine($"ToolTip内容:{toolTipText}");
    }
    // 如果后续ToolTip是复杂控件(比如自定义ToolTip),可以转型为对应的类型
    // else if (headerTextBlock.ToolTip is ToolTip customToolTip)
    // {
    //     // 处理自定义ToolTip的内容
    // }
}

注意事项

  • 一定要加类型判断(is关键字),避免因为Header不是TextBlock导致的空引用或转型错误
  • ToolTip属性的类型是object,如果设置的是字符串直接强转就行;如果是复杂的ToolTip控件,需要对应转型为ToolTip类型再处理内部内容

内容的提问来源于stack exchange,提问作者Joan Venge

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 11:07:28