View:
<Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApplication1" mc:Ignorable="d" Title="MainWindow" Height="350" Width="525"> <Window.DataContext> <local:ViewModel></local:ViewModel> </Window.DataContext> <Grid> <TreeView ItemsSource="{Binding MyItems}"> <TreeView.ItemTemplate> <HierarchicalDataTemplate ItemsSource="{Binding Children}"> <Button Foreground="Red" Content="{Binding Name}"></Button> </HierarchicalDataTemplate> </TreeView.ItemTemplate> </TreeView> </Grid>
ViewModel:
public class ViewModel { public ObservableCollection<TreeItemViewModel> MyItems { get; set; } public ViewModel() { MyItems = new ObservableCollection<TreeItemViewModel>(); MyItems.Add(new TreeItemViewModel() { Name = "lvl1" }); MyItems.Add(new TreeItemViewModel() { Name = "lvl1", Children =new ObservableCollection<TreeItemViewModel>() {new TreeItemViewModel() { Name = "lvl2" } } }); MyItems.Add(new TreeItemViewModel() { Name = "lvl1" }); } } public class TreeItemViewModel { public ObservableCollection<TreeItemViewModel> Children { get; set; } public string Name { get; set; } }
Result:
