1

如何扩展存在于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">

...... 等等

4

1 回答 1

1

您可以使用ExpandSubtree方法(msdn):

TreeViewItem.ExpandSubtree 方法

展开 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();
    }
}

如果您只想扩展主要项目,您应该使用IsExpanded属性 ( msdn )。

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;
    }
}
于 2013-10-29T18:40:51.607 回答