WPF Cannot see SelectedItem in TreeView

Bernard Lessard 1 Reputation point
2025-02-17T00:51:57.6933333+00:00

I'm using WPF .Net 9.0, I cannot see the SelectedItem element of the TreeView.

Anybody would know why ?

SelectedItem

.NET
.NET
Microsoft Technologies based on the .NET software framework.
4,107 questions
Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,828 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Hongrui Yu-MSFT 4,365 Reputation points Microsoft Vendor
    2025-02-17T01:32:43.0433333+00:00

    Hi, @Bernard Lessard. Welcome to Microsoft Q&A. 

    You could get the SelectedItem of TreeView in code, refer to the following method:

    MainWindow.xaml

    <Grid>
     <TreeView x:Name="MyTreeView" SelectedItemChanged="TreeView_SelectedItemChanged"></TreeView>
    </Grid>
    

    MainWindow.xaml.cs

    private void TreeView_SelectedItemChanged(object sender,RoutedPropertyChangedEventArgs<object> e)
    {
         var item = MyTreeView.SelectedItem;
    }
    

    Also note that the SelectedItem of TreeView is a Get property, which could only be obtained but not set. It cannot be set, so SelectedItem doesn't make much sense in XAML, and as you could see, SelectedItem is not in XAML. Picture1


    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.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.