Skip to content

SyncfusionExamples/How-to-bind-the-selecteditem-in-wpf-treeview-control

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 

Repository files navigation

How to bind the SelectedTreeItem to WPF TreeViewAdv?

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; }
}

Bind the SelectedTreeItem

About

This session explains about how to bind the selecteditem in wpf treeview control?

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 7

Languages