如何使用代码后面的代码扩展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">
......等等
答案 0 :(得分: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;
}
}