在Border中获取TreeViewItem的标记

时间:2017-06-01 09:21:16

标签: c# wpf

我为我的TreeView获得了这个XAML:

<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>

TreeViewItem Border中的Style {/ 1}},

我试图像这样在扩展上获取标记值:

 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 个答案:

答案 0 :(得分: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;
}