Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the height of a row in a WPF datagrid

Tags:

c#

wpf

datagrid

Can someone please advise me on how to do this?

I have tried

dtgMain.RowHeight;

but this always returns NAN.

like image 286
user589195 Avatar asked Jan 18 '23 16:01

user589195


2 Answers

Get a DataGridRow using VisualTreeHelper from data grid. Then use ActualHeight property on DataGridRow.

public static T GetFirstVisualChild<T>(DependencyObject depObj) where T : DependencyObject
{
    if (depObj != null)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
            if (child != null && child is T)
            {
                return (T)child;
            }

            T childItem = GetFirstVisualChild<T>(child);
            if (childItem != null) return childItem;
        }
    }

    return null;
}

Then:

DataGridRow row = GetFirstVisualChild<DataGridRow>(dtgMain);
if(row != null)
{
    row.ActualHeight;
}
like image 150
Amit Avatar answered Jan 21 '23 11:01

Amit


In case anyone needs the VB.NET version these days...

Public Shared Function GetFirstVisualChild(Of T As DependencyObject)(depObj As DependencyObject) As T
    If (depObj IsNot Nothing) Then
        Dim i As Integer
        For i = 0 To VisualTreeHelper.GetChildrenCount(depObj) - 1

            Dim child As DependencyObject = VisualTreeHelper.GetChild(depObj, i)
            If (child IsNot Nothing AndAlso TypeOf child Is T) Then

                Return CType(child, T)
            End If

            Dim childItem As T = GetFirstVisualChild(Of T)(child)
            If (childItem IsNot Nothing) Then Return childItem
        Next
    End If
    Return Nothing
End Function

then

Dim row As DataGridRow = CType(GetFirstVisualChild(Of DataGridRow)(grid), DataGridRow)
like image 33
Adam Jagosz Avatar answered Jan 21 '23 10:01

Adam Jagosz