WPF中TreeView如何实现展开一个节点其他节点关闭?
展开全部
楼主可以用两种思路来解决此问题。
第一种,运用TreeView的SelectedItemChanged事件
假设TreeView控件的name是treeview
c#参考代码:
private void treeview_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
TreeViewItem selected_item = treeview.SelectedItem as TreeViewItem;
TreeViewItem item;
if (selected_item != null)
{
for (int i = 0; i < treeview.Items.Count; i++)
{
item = treeview.Items[i] as TreeViewItem;
if (item != selected_item)
{
item.IsExpanded = false;
}
}
}
}
第二种思路是更改TreeViewItem的style啦!~
参考代码:
<Style TargetType="{x:Type TreeViewItem}">
<Style.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsSelected" Value="True"/>
<Condition Property="IsFocused" Value="True"/>
</MultiTrigger.Conditions>
<Setter Property="IsExpanded" Value="True"/>
</MultiTrigger>
<Trigger Property="IsSelected" Value="False" >
<Setter Property="IsExpanded" Value="False"/>
</Trigger>
</Style.Triggers>
</Style>
第一种,运用TreeView的SelectedItemChanged事件
假设TreeView控件的name是treeview
c#参考代码:
private void treeview_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
TreeViewItem selected_item = treeview.SelectedItem as TreeViewItem;
TreeViewItem item;
if (selected_item != null)
{
for (int i = 0; i < treeview.Items.Count; i++)
{
item = treeview.Items[i] as TreeViewItem;
if (item != selected_item)
{
item.IsExpanded = false;
}
}
}
}
第二种思路是更改TreeViewItem的style啦!~
参考代码:
<Style TargetType="{x:Type TreeViewItem}">
<Style.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsSelected" Value="True"/>
<Condition Property="IsFocused" Value="True"/>
</MultiTrigger.Conditions>
<Setter Property="IsExpanded" Value="True"/>
</MultiTrigger>
<Trigger Property="IsSelected" Value="False" >
<Setter Property="IsExpanded" Value="False"/>
</Trigger>
</Style.Triggers>
</Style>
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询