WPF DataBound treeview expandir / recolher
-
19-09-2019 - |
Pergunta
Eu estou apenas tentando encontrar uma maneira de controlar a expandir / recolher os nós TreeView
através do objeto que está vinculado. O objeto tem uma propriedade IsExpanded
, e eu quero usar isso para mostrar o nó TreeView
-se expandido ou recolhido com base nessa propriedade.
Aqui está o meu código:
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>
Solução
veio com solução. Muito simples:
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="IsExpanded" Value="{Binding IsNodeExpanded}">
</Setter>
</Style>
Assim, o estilo obtém o objeto ligado ao TreeViewItem e olha para o seu atributo IsNodeExpanded e atribui esse valor à propriedade TreeViewItem.IsExpanded. Se você adicionar Mode = TwoWay, eles notificam-se mutuamente (TreeViewItem dirá o objeto quando ele foi expandido).
Obrigado!
Outras dicas
FWIW, você pode estar interessado neste href="http://www.codeproject.com/KB/WPF/TreeViewWithViewModel.aspx" rel="nofollow noreferrer"> artigo que mostra como criar um MVVM baseado exibição de árvore usando uma abordagem genérica (n-nível).
Eu não estou sugerindo que há algo errado com a implementação de Carlo, mas eu achei que o artigo útil para compreender o controle TreeView, e MVVM em geral.