2015-01-02 63 views
0

我想知道在x:名稱網格的孩子在這種情況下:如何獲得網格的x:名稱?

<Grid x:Name="one" Grid.Row="0" Margin="49.667,15,15,15"> 
     <Grid x:Name="container1" Background="Red" Margin="10"/> 
     </Grid> 
    <Button Content="mov" Foreground="White" x:Name="first" HorizontalAlignment="Left" Margin="8,44.833,0,70.167" Width="29.334" Background="Black" Click="first_Click"/> 

和這裏的代碼當我點擊:

private void first_Click(object sender, System.Windows.RoutedEventArgs e) 
    { 

     var ttt = FindVisualChild<Grid>(one); 
     MessageBox.Show(ttt.ToString()); 

    } 

    private static T FindVisualChild<T>(DependencyObject parent) where T : DependencyObject 
    { 
     for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++) 
     { 
      DependencyObject child = VisualTreeHelper.GetChild(parent, i); 
      if (child != null && child is T) 
       return (T)child; 
      else 
      { 
       T childOfChild = FindVisualChild<T>(child); 
       if (childOfChild != null) 
        return childOfChild; 
      } 
     } 
     return null; 
    } 

當我點擊郵件只是表明此內容「System.Window.Controls.Grid」,而不是我想知道在這種情況下,「容器1」的x:名稱,那麼我請問,如果你有任何建議,我可以接收網格的x:名稱。

預先感謝您。

真誠

+1

你嘗試'ttt.Name'? – dkozl

+0

@dkozl是的,你是對的!!!非常感謝你......如果你回覆我的答案,我會標記它! – JayJay

回答

1

幸得dkozl提供你在OP的評論答案。我想提供一些額外的信息來補充它。

任何在XAML中向您公開的元素都可以作爲屬性在代碼隱藏中訪問(有一些例外,但大部分情況下,這些元素是對的)。

<Grid x:Name="one" Grid.Row="0" Margin="49.667,15,15,15"> 
     <Grid x:Name="container1" Background="Red" Margin="10"/> 
     </Grid> 
    <Button Content="mov" Foreground="White" x:Name="first" HorizontalAlignment="Left" Margin="8,44.833,0,70.167" Width="29.334" Background="Black" Click="first_Click"/> 

如果你願意,你可以訪問諸如

private void first_Click(object sender, System.Windows.RoutedEventArgs e) 
{ 
    this.one.Background = Brushes.Yellow; 
    this.one.Margin = new Thickness(0, 5, 10, 25); 
} 

你也不需要使用可視化樹查找,因爲你提供了一個名字給電網的電網特性,提供了代碼 - 背後與持有兩個網格的視圖相關聯。

你可以這樣做:

private void first_Click(object sender, System.Windows.RoutedEventArgs e) 
{ 
    MessageBox.Show(this.container1.Name); 
}