有人可以告诉我如何做到这一点吗?
我试过了
dtgMain.RowHeight;
但这总是返回NAN。
答案 0 :(得分:2)
从数据网格中使用VisualTreeHelper获取DataGridRow。然后在DataGridRow上使用ActualHeight属性。
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;
}
然后:
DataGridRow row = GetFirstVisualChild<DataGridRow>(dtgMain);
if(row != null)
{
row.ActualHeight;
}
答案 1 :(得分:1)
这很可能是因为网格尚未渲染。检查措施&amp;在尝试获取RowHeigth之前,将函数排列为渲染网格。
答案 2 :(得分:1)
这是NaN,因为你没有定义它。如果不手动设置,则由行内容的度量结果定义。
答案 3 :(得分:1)
如果有人现在需要VB.NET版本......
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
然后
Dim row As DataGridRow = CType(GetFirstVisualChild(Of DataGridRow)(grid), DataGridRow)