Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF find element with VisualTreeHelper vertical and horizontal

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!

like image 411
BendEg Avatar asked Sep 08 '25 14:09

BendEg


1 Answers

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

It's the most effective way because it's a .Net class specifically for your requirement.

For instance:

    // 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");
like image 129
Yael Avatar answered Sep 10 '25 13:09

Yael