How to get ToolTip from WPF Data Grid Column Header (DataGridTemplateColumn) in code?

Put the TextBlock in the HeaderTemplate of the column:

<DataGridTemplateColumn x:Name="col">
    <DataGridTemplateColumn.HeaderTemplate>
        <DataTemplate>
            <TextBlock Text="Current" ToolTip="Price" ToolTipService.InitialShowDelay="0" ToolTipService.Placement="Top"
                       ToolTipService.ShowDuration="999999" RenderOptions.BitmapScalingMode="NearestNeighbor"/>
        </DataTemplate>
    </DataGridTemplateColumn.HeaderTemplate>
</DataGridTemplateColumn>

…and find it in using the VisualTreeHelper:

private void Button_Click(object sender, RoutedEventArgs e)
{
    var columns = FindVisualChildren<System.Windows.Controls.Primitives.DataGridColumnHeader>(dataGrid)?
        .ToArray();

    if (columns != null)
    {
        int columnIndex = 1;
        if (columns.Length > columnIndex)
        {
            var textBlock = FindVisualChildren<TextBlock>(columns[columnIndex])?
            .FirstOrDefault();
            if (textBlock != null)
            {
                string tooltip = textBlock.ToolTip?.ToString();
                //...
            }
        }
    }
}

private static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
    {
        DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
        if (child is T t)
            yield return t;

        foreach (T childOfChild in FindVisualChildren<T>(child))
            yield return childOfChild;
    }
}

Browse More Popular Posts

Leave a Comment