Articles in this section
Category / Section

How to bind the SelectedTreeItem to WPF TreeViewAdv?

3 mins read

Follow the below steps to bind the SelectedTreeItem using MVVM in WPF 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.


<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>
public class ViewModel
{
    public ObservableCollection<Model> TreeItems { get; set; }
    public object SelectedItem { get; set; }

    public ViewModel()
    {
        TreeItems = PopulateData();
        SelectedItem = TreeItems[1]; // Sets "Calendar" as the initially selected item.
    }

    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;
    }
}
public class Model
{
    public string Header { get; set; }
}

output


View sample in GitHub
Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied