我想得到一个Button的父母的父母。我可以使用
获取父母Dim tempB As Button = CType(sender, Button)
Dim g1 As Grid = CType(tempB.Parent, Grid)
(在我的点击处理程序中)。但是如果我做的话
Dim g2 As New Object
g2 = g1.Parent
tempB.Content = g2.GetType
我得到NullReference Exception
答案 0 :(得分:5)
这是一个简单的C#代码段,它将为您提供所有单击按钮的父级:
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(GetParents(sender, 0));
}
private string GetParents(Object element, int parentLevel)
{
string returnValue = String.Format("[{0}] {1}", parentLevel, element.GetType());
if (element is FrameworkElement)
{
if (((FrameworkElement) element).Parent != null)
returnValue += String.Format("{0}{1}",
Environment.NewLine, GetParents(((FrameworkElement)element).Parent, parentLevel + 1));
}
return returnValue;
}