Category / Section
How to bind the selecteditem to WPF treeview control?
1 min read
Follow the below steps to bind the SelectedTreeItem using MVVM in TreeViewAdv.
Step 1: Create a Model class to responsible for exposing data from the ViewModel.
Step 2: Create a view model class and add the properties to bind the values.
Step 3: Define the TreeViewAdv control and bind the SelectedTreeItem and ItemSource property.
Step 4: Set the DataContext and ItemTemplate of TreeViewAdv to appear the appropriate items.
XAML
<Grid> <syncfusion:TreeViewAdv x:Name="TreeViewAdv" AllowMultiSelect="True" ItemsSource="{Binding TreeItems}" SelectedTreeItem="{Binding SelectedItem, Mode=TwoWay}" Width="150" Height="150"> <syncfusion:TreeViewAdv.DataContext> <local:ViewModel/> </syncfusion:TreeViewAdv.DataContext> <syncfusion:TreeViewAdv.ItemTemplate> <HierarchicalDataTemplate> <TextBlock Text="{Binding Header}" /> </HierarchicalDataTemplate> </syncfusion:TreeViewAdv.ItemTemplate> </syncfusion:TreeViewAdv> </Grid>
ViewModel
public class ViewModel { public ObservableCollection<Model> TreeItems { get; set; } public object SelectedItem { get; set; } public ViewModel() { TreeItems = PopulateData(); SelectedItem = TreeItems[1]; } private ObservableCollection<Model> PopulateData() { TreeItems = new ObservableCollection<Model>(); TreeItems.Add(new Model() { Header = "Mailbox" }); TreeItems.Add(new Model() { Header = "Calendar" }); TreeItems.Add(new Model() { Header = "Contacts" }); TreeItems.Add(new Model() { Header = "Drafts" }); TreeItems.Add(new Model() { Header = "Parent1" }); return TreeItems; } }
Model
public class Model { public string Header { get; set; } }