3

What is the easiest way, to search vertically and horizontally in the visual tree?

For example I want to find a control which is not in the list of parents from the control, which starts the search.

Here is a simple example (every box represents some UI control):

Visual-Tree

For example I start in a nested control (Search-Start) and want to find another nested control (Should be found).

What is the best way to do this? Parsing the complete visual tree seems not to be very effective... Thank you!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
BendEg
  • 20,098
  • 17
  • 57
  • 131
  • 2
    What do you mean with effective? Not working or not the most efficient way? Assuming you have no knowledge of the tree, and no element name to look for, traversing the (possibly) entire tree is the only to find what you need. – Willem van Rumpt Sep 17 '15 at 07:43
  • I mean as fast as possible :) I only have the information, that the control must be very near by a *root* element like a window. The control i like to search for is a `RadRibbonView`. – BendEg Sep 17 '15 at 07:44
  • 1
    Perhaps a [breadth-first](https://en.wikipedia.org/wiki/Breadth-first_search) might be more efficient then, but traverse the tree you will. – Willem van Rumpt Sep 17 '15 at 07:48

1 Answers1

4

There is no horizontaly search, class VisualTreeHelpers whom can help you Navigate on a WPF’s Visual Tree. Via Navigation you can implement all kinds of searches.

Its the most effective way because its a .Net class specifically for your requirement.

For instens:

// Search up the VisualTree to find DataGrid 
// containing specific Cell
var parent = VisualTreeHelpers.FindAncestor<DataGrid>(myDataGridCell);

// Search down the VisualTree to find a CheckBox 
// in this DataGridCell
var child = VisualTreeHelpers.FindChild<CheckBox>(myDataGridCell);

// Search up the VisualTree to find a TextBox 
// named SearchTextBox
var searchBox = VisualTreeHelpers.FindAncestor<TextBox>(myDataGridCell, "SeachTextBox");

// Search down the VisualTree to find a Label
// named MyCheckBoxLabel
var specificChild = VisualTreeHelpers.FindChild<Label>(myDataGridCell, "MyCheckBoxLabel");
Yael
  • 1,566
  • 3
  • 18
  • 25
  • 2
    Works perfectly. I used `Window parentWindow = Window.GetWindow(current);` to find the *root* and then `FindChild()` to get the one i need :) Thank you! – BendEg Sep 17 '15 at 08:42
  • 1
    I had to combine @BendEg 's solution with Yael 's solution. Thanks – sm2mafaz Jul 08 '19 at 07:52