I’ve been having issues with the TreeView
in WPF. This control makes it very hard to access the TreeViewItem
s it’s showing.
On several occasion
Admittedly this is not straightforward but you can probably still do this while keeping a separation which does not require you to access the TreeViewItems
knowingly. The essence in WPF is binding as already noted by Kent Boogaart in your other question, here however you need to somehow deal with events. Your view-model needs to fire a BringIntoView
event of its own while the view needs to react.
The easiest method might be to add a EventSetter
on Loaded
to make the TreeViewItems
subscribe to said event on their DataContext
which should be your view-model (if it isn't you can wait for DataContextChanged
).
No, I dont see in what way accessing the items of a treeview is wrong.
I think the difficulties you are encountering are because you aren't seeing the treeview as it should be.
A leaf has a parent, but no children. A node can have a parent, and can have children. A node without a parent is a root.
Based on these principles (SourceMaking Composite pattern) you should be able to do whatever you want using recursivity. (in both XAML and code)
Take a look at Simplifying the WPF TreeView by Using the ViewModel Pattern article by Josh Smith. I hope it helps.
I’ve come to the conclusion that it can’t be altogether wrong. The first piece of evidence comes from Bea Stollnitz’s post about ListView: if one of the WPF developers explains how this might be done, it can’t be that wrong.
The other piece of evidence comes from this highly-voted question/answer: MVVM madness. MVVM undoubtedly has its benefits, but sometimes the cost of following MVVM is so high that it’s just silly following through with it, especially in a small one-man application. Do you really want to expose IsSelected and IsExpanded the way you’re supposed to?
As a result, I felt justified to try and figure out how to expose the TreeViewItem
corresponding to an item with less effort from the developer, under the assumption that they will never need the more advanced features that resulted in TreeViewItem
s being this hard to access (like displaying the same ViewModels in multiple different controls... how often have you needed that!...)
I posted the result of this effort as an answer on another question.