Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the row of image in a DataGrid?

Tags:

c#

.net

wpf

I have images in one of the columns of my WPF DataGrid. I need to generate dynamic tooltips for them so I created a handler for the ToolTipOpening event. But the problem is that sender of this event is instance of Image class and it doesn't have any information about row where event happened while I need it to generate tooltips. I have CellContentTemplate for this column defined like this

<DataTemplate x:Key="SomeTemplate" x:Shared="true">
    <Image Name="SomeImage"
           Style="{StaticResource SomeStyle}"
           Width="16"
           Height="16"
           HorizontalAlignment="Center"
           VerticalAlignment="Center"
           Stretch="None"
           ToolTipOpening="SomeTooltipHandler"/>
</DataTemplate>

Any ideas how get a row number in my handler?

like image 904
KirillSk Avatar asked Nov 19 '25 22:11

KirillSk


1 Answers

Since an Image is a DependencyObject, you can find its ancestor using the VisualTreeHelper.GetParent. So, to find the DataGrid for instance:

public static DataGrid FindDataGridAncestor(DependencyObject dependencyObject)
{
        DependencyObject target = dependencyObject;
        do
        {
            target = VisualTreeHelper.GetParent(target);
        }
        while (target != null && !(target is DataGrid));

        return target as DataGrid;
}

Usage:

DataGrid myGrid = FindDataGridAncestor(myImage);
like image 148
Blachshma Avatar answered Nov 22 '25 13:11

Blachshma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!