WPF DataBound 树视图展开/折叠
Posted
技术标签:
【中文标题】WPF DataBound 树视图展开/折叠【英文标题】:WPF DataBound treeview expand / collapse 【发布时间】:2010-12-15 14:47:23 【问题描述】:我只是想找到一种方法来通过它们绑定到的对象来控制TreeView
节点的展开/折叠。该对象有一个IsExpanded
属性,我想用它来显示TreeView
节点本身基于该属性展开或折叠。
这是我的代码:
C#:
public partial class Window2 : Window
public Window2()
InitializeComponent();
this.DataContext = new List<Parent>() Base.GetParent("Parent 1"), Base.GetParent("Parent 2") ;
public class Base
public string Name get; set;
public bool IsExpanded get; set;
public static Parent GetParent(string name)
Parent p = new Parent() Name = name ;
p.Children.Add(new Child() Name = "Child 1", GrandChildren = new ObservableCollection<GrandChild>() new GrandChild() Name = "Grandchild 1" );
p.Children.Add(new Child() Name = "Child 2", GrandChildren = new ObservableCollection<GrandChild>() new GrandChild() Name = "Grandchild 1" );
p.Children.Add(new Child() Name = "Child 3", GrandChildren = new ObservableCollection<GrandChild>() new GrandChild() Name = "Grandchild 1" );
return p;
public class Parent : Base
public ObservableCollection<Child> Children get; set;
public Parent()
this.Children = new ObservableCollection<Child>();
public class Child : Base
public ObservableCollection<GrandChild> GrandChildren get; set;
public Child()
this.GrandChildren = new ObservableCollection<GrandChild>();
public class GrandChild : Base
XAML:
<Window x:Class="HeterogeneousExperimentExplorer.Window2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:HeterogeneousTree"
Title="Window2" Height="300" Width="300">
<Window.Resources>
<HierarchicalDataTemplate DataType="x:Type local:Parent" ItemsSource="Binding Children">
<TextBlock Text="Binding Name" />
<HierarchicalDataTemplate.ItemTemplate>
<HierarchicalDataTemplate DataType="x:Type local:Parent" ItemsSource="Binding GrandChildren">
<TextBlock Text="Binding Name" />
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<TextBlock Text="Binding Name" />
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</Window.Resources>
<Grid>
<TreeView ItemsSource="Binding" />
</Grid>
</Window>
【问题讨论】:
【参考方案1】:想出了解决办法:
<Style TargetType="x:Type TreeViewItem">
<Setter Property="IsExpanded" Value="Binding IsNodeExpanded"/>
</Style>
因此,样式获取绑定到 TreeViewItem 的对象并查看其 IsNodeExpanded 属性,并将该值分配给 TreeViewItem.IsExpanded 属性。如果添加 Mode=TwoWay,它们会相互通知(TreeViewItem 会在对象展开时通知对象)。
【讨论】:
大约晚了(9 年后) - 但是您在 XML 中的哪个位置放置了 Style 元素? @NirMH 它应该在TreeView.Resources
记得输入Mode=TwoWays
以获得全部功能
也有用的链接***.com/questions/1487144/autoexpand-treeview-in-wpf以上是关于WPF DataBound 树视图展开/折叠的主要内容,如果未能解决你的问题,请参考以下文章