展开树视图中的特定项

本文关键字:视图 | 更新日期: 2023-09-27 18:37:17

如何使用

代码隐藏扩展TreeView中存在的项目? 例如,当我单击菜单时,我可以展开TreeView中的特定项目。

private void MenuItem_Click(object sender, RoutedEventArgs e)
    {
        // expand the 3rd item in my treeview
    }

XAML 中的代码:

<TreeView Height="525" HorizontalAlignment="Left" Margin="2,47,0,0" Name="treeView1" VerticalAlignment="Top" Width="168" FontFamily="Times New Roman" FontSize="12">
        <TreeViewItem Header="PL3 Line 1" IsExpanded="False">
            <TreeViewItem Selected="TreeViewItem_Selected">
                <TreeViewItem.Header>
                    <StackPanel Orientation="Horizontal">
                        <Image Source="/MonitoringSystemOfficeArea;component/Images/Computer.png" Height="22" Width="26"></Image>
                        <Label Content="Live Update" Width="70"></Label>
                    </StackPanel>
                </TreeViewItem.Header>
            </TreeViewItem>
            <TreeViewItem Selected="TreeViewItem_Selected_1">
                <TreeViewItem.Header>
                    <StackPanel Orientation="Horizontal">
                        <Image Source="/MonitoringSystemOfficeArea;component/Images/Calender.png" Height="24" Width="27"></Image>
                        <Label Content="Archives" Width="70"></Label>
                    </StackPanel>
                </TreeViewItem.Header>
            </TreeViewItem>
            <TreeViewItem Selected="TreeViewItem_Selected_100">
                <TreeViewItem.Header>
                    <StackPanel Orientation="Horizontal">
                        <Image Source="/MonitoringSystemOfficeArea;component/Images/Aha-Soft-Large-Calendar-Calendar.ico" Height="24" Width="27"></Image>
                        <Label Content="Archives / days" Width="88"></Label>
                    </StackPanel>
                </TreeViewItem.Header>
            </TreeViewItem>
        </TreeViewItem>
        <TreeViewItem Header="PL7 Line 2" IsExpanded="False">

......等等

展开树视图中的特定项

您可以使用

ExpandSubtree方法(msdn):

TreeViewItem.ExpandSubtree Method

展开 TreeViewItem

控件及其所有子 TreeViewItem 元素。

private void MenuItem_Click(object sender, RoutedEventArgs e)
{
    // expand the 3rd item and all its child in treeview      
    TreeViewItem tvi = treeView1.Items[2] as TreeViewItem;
    if (tvi != null)
    {
        tvi.ExpandSubtree();
    }
}

如果只想展开主项,则应使用属性 (msdn) IsExpanded

private void MenuItem_Click(object sender, RoutedEventArgs e)
{
    // expand the 3rd item in treeview      
    TreeViewItem tvi = treeView1.Items[2] as TreeViewItem;
    if (tvi != null)
    {
        tvi.IsExpanded = true;
    }
}

如果要折叠项目集IsExpanded为 false:

private void MenuItem_Click(object sender, RoutedEventArgs e)
{
    // collapse the 3rd item in treeview      
    TreeViewItem tvi = treeView1.Items[2] as TreeViewItem;
    if (tvi != null)
    {
        tvi.IsExpanded = false;
    }
}