For my treeview I have two different classes that provide the ItemsSource.
public class TreeViewModel : ViewModelBase
{
public ObservableCollection
You should only have to declare the HierarchicalDataTemplate
for NodeViewModel
as this is the only thing showing in the TreeView
, and bind the actual ItemSource
to the TreeView
Full Example
Xaml:
Code:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public TreeViewModel TreeModel
{
get
{
return new TreeViewModel
{
Items = new ObservableCollection{
new NodeViewModel { Name = "Root", Children = new ObservableCollection {
new NodeViewModel { Name = "Level1" , Children = new ObservableCollection{
new NodeViewModel{ Name = "Level2"}}} } }}
};
}
}
}
public class TreeViewModel
{
public ObservableCollection Items { get; set; }
}
public class NodeViewModel
{
public string Id { get; set; }
public string Name { get; set; }
public ObservableCollection Children { get; set; }
}
Result: