UWP TreeView SelectItem MVVM

득권 천 61 Reputation points
2022-04-07T02:09:54.597+00:00

Hello
I want to get the selected information from the treeview from the ViewModel when the button is pressed.

<winui:TreeView HorizontalAlignment="Left"
ItemsSource="{Binding TreeDataSource}"
Grid.Column="0"
Background="Aqua">
<winui:TreeView.ItemTemplate>
<DataTemplate>
<winui:TreeViewItem ItemsSource="{Binding Childrens}" Content="{Binding Name}" IsExpanded="True"/>
</DataTemplate>
</winui:TreeView.ItemTemplate>

</winui:TreeView>

Universal Windows Platform (UWP)
{count} votes

Accepted answer
  1. Roy Li - MSFT 31,826 Reputation points Microsoft Vendor
    2022-04-07T03:30:44.373+00:00

    Hello,

    Welcome to Microsoft Q&A!

    TreeView has TreeView.SelectedItem Property and TreeView.SelectedItems Property. You can use these properties to get the content of selected nodes directly. If multiple selections are enabled, SelectedItem contains the first item in the SelectedItems collection.

    Like this:

    MyDataModel selectedItem= myTreeView.SelectedItem as MyDataModel   
    

    For more information about TreeView, you could refer to TreeViews in UWP Apps.

    Thank you.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful