Start new WPF application. Add TreeView control from toolbox.
Add one label.
My XAML looks like this:
<Window x:Class="MVVMtreeView.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TreeView HorizontalAlignment="Left" Height="206" Margin="10,10,0,0" VerticalAlignment="Top" Width="497"/>
<Label Content="Label" HorizontalAlignment="Left" Margin="10,284,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.421,0.462" Width="497"/>
</Grid>
</Window>
Then add model, I called it TreeViewModel, and it looks like this:
namespace MVVMtreeView
{
public class TreeViewModel
{
public List<string> TreeViewModels { get; set; }
public TreeViewModel()
{
TreeViewModels = new List<string>();
TreeViewModels.Add("test");
}
}
}
In "code behind", in MainWindow.xaml.cs, in MainWindow method, add line DataContext = new TreeViewModel(); so, in my case MainWindow.xaml.cs looks like this:
namespace MVVMtreeView
{
///
/// Interaction logic for MainWindow.xaml
///
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new TreeViewModel();
}
}
}
Now, bind tree view to a model, that means in the XAML (in my case MainWindow.xaml), add ItemsSource="{Binding Path=TreeViewModels}", I also add name to a tree view, then bind label content, so now my XAML looks like this:
<Window x:Class="MVVMtreeView.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TreeView Name="tv" ItemsSource="{Binding Path=TreeViewModels}" HorizontalAlignment="Left" Height="206" Margin="10,10,0,0" VerticalAlignment="Top" Width="497"/>
<Label Content="{Binding ElementName=tv, Path=SelectedItem}" HorizontalAlignment="Left" Margin="10,284,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.421,0.462" Width="497"/>
</Grid>
</Window>
Example you can download from here.