2011-08-05 68 views
1

我想獲取Button的父項的父項。我能夠得到父母使用如何獲得wpf按鈕的父項的父項

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

回答

4

下面是一個簡單的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; 
    }