2017-06-01 46 views
-3

我得到這個XAML爲我的TreeView:獲取樹型視圖的標籤在邊境

<TreeView x:Name="treeViewSL" FontSize="14" Margin="10,5,875,10" Grid.Row="1" TreeViewItem.Expanded="TreeViewItem_Expanded" ItemContainerStyle="{StaticResource TreeViewItemLayer}" ItemsSource="{Binding RootNode}" > 
         <TreeView.ItemTemplate> 
          <HierarchicalDataTemplate DataType="{x:Type OfflineSparepartEntities:ArtikelTreeNode}" ItemsSource="{Binding ChildNodes}" > 
           <Border BorderThickness="1" BorderBrush="DarkGray" CornerRadius="3" Margin=" 0 2" Style="{StaticResource TreeViewBorderStyle}"> 
            <TreeViewItem x:Name="trItem" Header="{Binding NodeText}" Tag="{Binding NodeValue}" /> 
           </Border> 
          </HierarchicalDataTemplate> 
         </TreeView.ItemTemplate> 

        </TreeView> 

所以在BorderStyle東西TreeViewItem

我試圖讓展開這樣的標記值:

private void TreeViewItem_Expanded(object sender, RoutedEventArgs e) 
     { 
      TreeViewItem item = e.Source as TreeViewItem; 

      if((item.Items.Count ==1) && (item.Items[0] is string)) 
      { 
       item.Items.Clear(); 


      } 

     } 

但是這給了我每一次空異常,似乎他找不到正確的TreeViewitem ...任何想法?

回答

1

OriginalSource物業轉換爲TreeViewItem。這是正在擴大的項目。然後,您應該能夠在可視化樹中找到子女TreeViewItem。試試這個:

private void TreeViewItem_Expanded(object sender, RoutedEventArgs e) 
{ 
    TreeViewItem item = e.OriginalSource as TreeViewItem; 
    if (item != null) 
    { 
     TreeViewItem child = GetChildOfType<TreeViewItem>(item); 
     if (child != null && child.Tag != null) 
      MessageBox.Show(child.Tag.ToString()); 
    } 
} 

private static T GetChildOfType<T>(DependencyObject depObj) where T : DependencyObject 
{ 
    if (depObj == null) 
     return null; 

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++) 
    { 
     var child = VisualTreeHelper.GetChild(depObj, i); 

     var result = (child as T) ?? GetChildOfType<T>(child); 
     if (result != null) 
      return result; 
    } 
    return null; 
} 
+0

非常好,看起來他拉了我的treeviewitem周圍的邊界,現在它得到的物品 –