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
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.