问题
I'd like to display the following structure in a WPF Treeview:
public class Group{
public string Groupname;
public IEnumerable<Group> Groups;
public Ienumerable<User> Member;
}
My ViewModel looks like this:
public class ViewModel{
public Group RootGroup;
}
I think the XAML Code should look like this:
<TreeView>
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource={Binding ViewModel.RootGroup}>
<TextBlock Text={Binding Groupname}/>
<HierarchicalDataTemplate ItemsSource={Binding Member}>
<TextBlock Text={Binding Displayname}/>
</HierarchicalDataTemplate>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
What I want it to look like:
RootGroup-Name
-Member1
-Member2
-Member3
-Member4
-SubGroup1
-Member1
-Sub-SubGroup1
-Member1
-SubGroup2
-Sub-SubGroup2
-Sub-Sub-SubGroup1
-Member1
I've bound the DataContext to itself so this shouldn't be the reason why my TreeView wont show anything.
回答1:
Finally I just found the solution by myself:
<TreeView Grid.Row="1" ItemsSource="{Binding MVM.RootGroup}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Groups}">
<TextBlock Text="{Binding Name}"/>
<HierarchicalDataTemplate.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Members}">
<TextBlock Text="{Binding Name}"/>
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Displayname}"/>
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
But the Users from the first level get lost.
回答2:
To achieve that behavior you should change ViewModel
and ItemTemplate
. Here some code that I've used in my project.
<HierarchicalDataTemplate DataType="local:GItemViewModel" ItemsSource="{Binding Path=Nodes}">
<DockPanel>
<TextBlock Margin="2" VerticalAlignment="Center" Text="{Binding Path=Name}" FontSize="12" />
</DockPanel>
</HierarchicalDataTemplate>
ViewModel for this. Here Name
is name for group and name for member depends on the object. Member is the node with Nodes
is set to null.
public sealed class GItemViewModel : INotifyPropertyChanged
{
private string _name = string.Empty;
public string Name
{
get { return _name; }
set { _name = value; NotifyPropertyChanged( "Name" ); }
}
public ObservableCollection<GItemViewModel> Nodes { get; set; }
...
}
I hope this helps.
Update
To set root element Name
you can add into the ViewModel elemet like this. And bind the root collection to the treeView
like this.
GItemViewModel vm = new GItemViewModel();
GItemViewModel root = new GItemVieModel() { Name = "Root" };
vm.Nodes.Add( root );
treeView.ItemsSource = vm.Nodes;
来源:https://stackoverflow.com/questions/33561390/binding-a-wpf-treeview-to-multiple-lists