wpf 动态展开树状视图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12116824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 05:06:02  来源:igfitidea点击:

Dynamically expand treeview

wpfvb.nettreeviewexpandtreeviewitem

提问by surpavan

I am using a class as follows:

我正在使用一个类,如下所示:

Class DirectoryViewItem
    Property Namee As String
    Property Iconn As BitmapImage
    Property Path As String
    Property SubNodes As New List(Of DirectoryViewItem)
End Class

and the xaml I used is:

我使用的 xaml 是:

<TreeView Name="DirectoryTreeView"
          TreeViewItem.Expanded="DirectoryTreeView_Expanded"
          Grid.Row="0">
    <TreeView.ItemTemplate >
        <HierarchicalDataTemplate ItemsSource="{Binding SubNodes}">
            <StackPanel Orientation="Horizontal">
                <Image Source="{Binding Iconn}"
                       Width="32" Height="32"
                       VerticalAlignment="Center" HorizontalAlignment="Left" />
                <TextBlock Text="{Binding Namee}"
                           VerticalAlignment="Center" HorizontalAlignment="Left" />
            </StackPanel>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

The code is working fine, now I want to expand the 3 or some x node through code, and I found the solution to use something like this:

代码工作正常,现在我想通过代码扩展 3 或一些 x 节点,我找到了使用这样的解决方案:

CType(DirectoryTreeView.Items(3), TreeViewItem).ExpandSubtree()

However, I found that the CTypehere is not TreeViewItembut it is my DirectoryViewItemtype, could you please tell me how I can solve this, I think I need to change the default appearance of use a TreeViewItem.Headerfor that I can display the items as well as perform the expand function. Could you please tell me how I can do this. Thank you.

但是,我发现CType这里不是TreeViewItem但它是我的DirectoryViewItem类型,请告诉我如何解决这个问题,我想我需要更改 use a 的默认外观,TreeViewItem.Header以便我可以显示项目以及执行扩展功能。你能告诉我我怎么能做到这一点。谢谢你。

回答by H.B.

  1. Use the TreeView.ItemContainerStyleto bind IsExpandedto a property on your items.
  2. Implement ExpandSubtreeon your items (all it needs to do is set that bound property on your items to truerecursively).
  1. 使用TreeView.ItemContainerStyle绑定IsExpanded到项目上的属性。
  2. ExpandSubtree在您的项目上实现(它需要做的就是将项目上的绑定属性设置为true递归)。