Shown below are two useful methods that works on a VisualTreeHelper class and makes it easy to access elements that are otherwise not easy to access. I would show you concrete examples to use it later, but for now here is the code for the two methods.
The above method can be used to search for any UIElement given its parent as a parameter. For example, GetChildrenOfType<Button>(StackPanel1) returns a list of all buttons hosted inside the StackPanel. A cut down version of this method is where it just returns the first item.
The method is again easy to use.
So where did I use these methods? Working with TreeView?
How do I expand a TreeView completely?
This not a straight-forward issue since we know that most of the UI in WPF is virtualized unless otherwise specified. So I have a tree view and I would to completely expand the list. So how do I do it? What are the issues? If you set the TreeView IsExpanded property to true, it only expands the first level of children. So we need to repeat the process again on the children of the just appeared children. But they are not in the Visual Tree unless the lay out is updated. The method shown below works great to toggle expand/collapse of a tree view.
Bea just posted a simpler way to do this.