WPF: Select TreeViewItem broken past the root level

后端 未结 3 1020
太阳男子
太阳男子 2020-12-18 15:29

I\'m trying to select a TreeViewItem by ID, but having problems getting it to work past the first (root) level. I\'ve done so much reading round on this and am using the met

3条回答
  •  情深已故
    2020-12-18 16:06

    I think it doesn't work since item is collapsed and its container is not instantiated. Thus trying to select TreeViewItem directly is definitely not the best way to go.

    Instead we use MVVM approach. Every viewmodel object should have IsSelected property. Then you bind TreeViewItem.IsSelected propery to it.

    In your case it would go like this

    CS:

    public interface INestable : INotifyPropertyChanged
    {
      string ID { get; set; }
    
      // Make sure you invoke PropertyChanged in setter
      bool IsSelected { get; set; } 
    
      event PropertyChangedEventHandler PropertyChanged;
      ...
    }
    

    XAML:

    
      
       
      
    
    

    Now you can go through your model and set IsSelected property there.

    You may also want to track IsExpanded property in a same way...

    To get more information about TreeView read this wonderful article by Josh Smith: Simplifying the WPF TreeView by Using the ViewModel Pattern

    Hope this helps.

提交回复
热议问题