VisualTreeHelper VisualTreeHelper VisualTreeHelper Class

Provides utility methods that can be used to traverse object relationships (along child-object or parent-object axes) in the visual tree of your app.

Syntax

Declaration

public sealed class VisualTreeHelperpublic sealed class VisualTreeHelperPublic NotInheritable Class VisualTreeHelper

Remarks

The visual tree

The purpose of the VisualTreeHelper class is to help with discovery of objects that you are looking for in the runtime tree of objects, but there isn't a more direct object-relationship API available for your scenario. Sometimes, you won't know the exact type or name of the object. Or perhaps you know that a specific object appears somewhere in the tree but you don't know the exact position. For these types of scenarios, VisualTreeHelper is helpful because you can recursively find all the objects in the visual tree and then look through this set and look for a match based on your criteria.

The visual tree for an app can be conceptualized as a filtered representation of the larger object tree of an app's objects and properties. Only the objects that have a rendering implication are present in a visual tree. For example, a collection class would not be part of the visual tree. Instead, the visual tree abstracts any collection into a "children" concept.

However, the visual tree can also include objects that are not represented as XAML elements in a page's XAML markup. This is because the visual tree adds objects that are the composited parts of controls. These control parts can come from an applied control template, which is usually XAML from a resource dictionary item, or from a presenter.

XAML markup and a visual tree don't match exactly node-for-node because XAML is designed for markup, and ease of use during markup definition, so it sometimes has extra elements. For example, XAML has property elements, which sets property values if one element is found nested within another. In a visual tree, this would just look like a property on an object being set by another object. XAML also has a concept of a content property, where the property being set is not explicitly designated in markup. For more info on the specific terminology and the rules for XAML, see XAML overview.

The visual tree is used internally for the UI rendering process, but knowing the structure of the visual tree is important for certain scenarios, such as writing or replacing a control template, or analysis of a control's structure and parts at run-time. For these scenarios, the Windows Runtime provides the VisualTreeHelper API that can examine the visual tree in a more generalized way. (You could theoretically construct such a tree using object-specific parent and children properties too, but you'd have to know exactly which properties each element supported, and that's difficult to discover or manage.)

You typically combine several VisualTreeHelper API calls to write your own helper functions that investigate the visual tree in ways that are specific to your own app's scenarios.

Traversing a visual tree

Traversing the object tree (sometimes known colloquially as walking the tree) is a common technique in object models. You use properties that either reference child objects (typically these are collections) or parent relationships to a containing object (usually this is done from within a collection, and returns the collection itself). As a rough description of the process, you call a succession of child properties and parent properties, or perhaps helper methods, to navigate the axes of the object tree until you retrieve a value that contains the object that you were looking for. As a general rule, you should be able to construct your content in XAML such that you do not need to query the structure of the tree extensively. To avoid the need to traverse the tree, you should give XAML elements a value for the x:Name / Name attribute in the XAML markup that creates them. This creates an immediate reference that is available for run-time code access, and that's a much less error-prone technique for getting object references than walking the tree is. Alternatively, if you are creating objects through code rather than XAML, you should declare private fields or variables that retain object reference at run-time. There's typically no need to traverse the tree to find objects that are created in your own code.

However, there are cases where it is not possible or practical to give an object a name and keep an object reference in scope. One such scenario is if you are adding dynamic content that is supplied by the user or supplied by data binding, or using view models and business objects. In these cases you cannot always predict the number of items added or the structure of a control and its children. Another scenario is examining an applied template for a control, or a composited section of a control or presenter content.

Traversing the tree downwards (away from the root) multiple levels can be done using GetChildrenCount(DependencyObject) for nonzero values and then GetChild(DependencyObject, Int32) to request a specific index. You might have to use try/catch techniques or the equivalent if you are trying to cast elements as specific UIElement subtypes. Generally the VisualTreeHelper API return elements as a DependencyObject and you will need to cast it in order to do anything useful (even for as simple an operation as checking its Name value).

Windows 8 behavior

UI threading

Windows 8 permitted VisualTreeHelper function calls that were referencing objects on the wrong (not the current) UI thread. Starting with Windows 8.1, the function throws an exception if it's not being called from the current UI thread. Accounting for this new behavior should be a very uncommon app migration scenario; it's difficult to get UI elements across threads in the first place.

Apps that were compiled for Windows 8 but running on Windows 8.1 use the Windows 8.1 behavior, and will throw specifically on the VisualTreeHelper function call rather than on any downstream app code that uses a cross-thread object.

App UI for On-Screen Keyboard

Windows 8 had an internally implemented logic that would associate a ScrollViewer with the overall app UI whenever the user invokes the On-Screen Keyboard. This On-Screen Keyboard is a specific accessibility feature that users request through the Ease of Access Center. It's not the same as the soft keyboard that can appear in app UI for text input controls, if the system detects no keyboard device. What the internal ScrollViewer does here is to make it possible to scroll the area where the app is, if scrolling it is forced because the keyboard is taking UI space.

Starting with Windows 8.1, the system still has UI/layout behavior when the On-Screen Keyboard appears, but it no longer uses this internally created ScrollViewer. Instead it uses a dedicated internal control that app code can't change or inspect.

Most aspects of this behavior change don't affect apps at all. However, your app might have anticipated this behavior, by providing an implicit Style for ScrollViewer that's meant to change the layout, or by walking the tree with VisualTreeHelper to find this internally created ScrollViewer and alter it at run-time. For an app that is compiled for Windows 8.1 that code won't be useful.

Apps that were compiled for Windows 8 but running on Windows 8.1 continue to use the Windows 8 behavior.

Examples

Here's an example of a utility function that can copy a list of child elements of a particular type from within a visual tree. It uses the basic traversal methods GetChildrenCount(DependencyObject) and GetChild(DependencyObject, Int32). It uses recursion so that elements can be found no matter what level of nesting within intermediate containers exists. It also uses an IsSubclassOf extension method from System.Reflection that extends the type comparison to consider subtypes as a match for a Type.

internal static void FindChildren<T>(List<T> results, DependencyObject startNode)
  where T : DependencyObject
{
    int count = VisualTreeHelper.GetChildrenCount(startNode);
    for (int i = 0; i < count; i++)
    {
        DependencyObject current = VisualTreeHelper.GetChild(startNode, i);
        if ((current.GetType()).Equals(typeof(T)) || (current.GetType().GetTypeInfo().IsSubclassOf(typeof(T))))
        {
            T asType = (T)current;
            results.Add(asType);
        }
        FindChildren<T>(results, current);
    }
}

Methods summary

Explicitly removes all references from a target UIElement, with the goal of cleaning up reference cycles.

Retrieves a set of objects that are located within a specified x-y coordinate point of an app UI. The set of objects represents the components of a visual tree that share that point.

Retrieves a set of objects that are located within a specified x-y coordinate point of an app UI. The set of objects represents the components of a visual tree that share that point.

Retrieves a set of objects that are located within a specified Rect frame of an app UI. The set of objects represents the components of a visual tree that share a rectangular area, and might include elements that overdraw.

Retrieves a set of objects that are located within a specified Rect frame of an app UI. The set of objects represents the components of a visual tree that share a rectangular area, and might include elements that overdraw.

Using the provided index, obtains a specific child object of the provided object by examining the visual tree.

Returns the number of children that exist in an object's child collection in the visual tree.

Retrieves a collection of all open popup controls from the target Window.

Returns an object's parent object in the visual tree.

Methods

  • DisconnectChildrenRecursive(UIElement)
    DisconnectChildrenRecursive(UIElement)
    DisconnectChildrenRecursive(UIElement)
    DisconnectChildrenRecursive(UIElement)

    Explicitly removes all references from a target UIElement, with the goal of cleaning up reference cycles.

    public static void DisconnectChildrenRecursive(UIElement element)public static void DisconnectChildrenRecursive(UIElement element)Public Static Function DisconnectChildrenRecursive(element As UIElement) As voidpublic static void DisconnectChildrenRecursive(UIElement element)

    Parameters

    Remarks

    This method is not intended for typical app or user code scenarios. Instead, it is intended for scenarios where a visual tree is hosted by some other application, such as a designer or code analysis tool. In most cases the scenario is that the visual tree is being cleared because it is about to be rebuilt based on saved information plus changes.

  • FindElementsInHostCoordinates(Point, UIElement)
    FindElementsInHostCoordinates(Point, UIElement)
    FindElementsInHostCoordinates(Point, UIElement)
    FindElementsInHostCoordinates(Point, UIElement)

    Retrieves a set of objects that are located within a specified x-y coordinate point of an app UI. The set of objects represents the components of a visual tree that share that point.

    public static IIterable<UIElement> FindElementsInHostCoordinates(Point intersectingPoint, UIElement subtree)public static IIterable<UIElement> FindElementsInHostCoordinates(Point intersectingPoint, UIElement subtree)Public Static Function FindElementsInHostCoordinates(intersectingPoint As Point, subtree As UIElement) As IIterable( Of UIElement )public static IIterable<UIElement> FindElementsInHostCoordinates(Point intersectingPoint, UIElement subtree)

    Parameters

    • intersectingPoint

      The point to use as the determination point. This point is using the coordinate space of the app window, not of any specific element (and not of subtree if specified).

    • subtree

      An object to search for. If the subtree object exists in the overall set of elements that exist at the specified intersectingPoint coordinates, then the return value contains only the subtree object and any objects that have a higher z-order than subtree, listed by inverse of z-order. If the subtree object doesn't exist at intersectingPoint coordinates, the return value will be empty.

    Returns

    • An enumerable set of UIElement objects in the visual tree composition at the specified point, listed by inverse of z-order.

    Remarks

    The return value is not a single element, it is a collection. The collection can have more than one element because there can be multiple UI elements stacked over each other in a z-order. The conventional hit-testing techniques exposed by the input event handlers, such as the sender value for a PointerPressed event, only account for the topmost element that has the highest z-order. FindElementsInHostCoordinates(Point, UIElement) methods return the whole stack of elements that share that point or area in the app UI, listed by inverse of z-order. Using FindElementsInHostCoordinates(Point, UIElement) can thus be useful for examining cases where you've intentionally or unintentionally stacked elements. You may want to correct the order for rendering and hit-testing, or examine that order for other reasons.

    FindElementsInHostCoordinates(Point, UIElement) is useful for three scenarios: basic hit testing, hit testing that is filtering for a specific element, and determining whether there are elements in a visual tree that are overdrawing at the same point.

    Basic hit testing

    For basic hit testing, the goal is to discover which element is highest in the z-order of an app UI at a given point in x-y coordinates. In addition to being the element that draws topmost in the rendered UI, this element is also important because it's the reported event source if there are user interactions such as pointer events. You might have hit testing scenarios where you want to know what element exists at the top z-order before any input event takes place, so that you can anticipate it and perhaps correct any mistakes in z-order placement.

    For this scenario, you should pass the point you're interested in hit-testing as the value of the intersectingPoint parameter. For the subtree parameter, you can pass it as null. Or you can specify subtree to be some element that you know is the root visual of a page, or is otherwise some element that you want to be the final stop for hit testing.

    The element that is topmost in the z-order is always the first element in the returned IEnumerable of UIElement items. So for basic hit testing you're usually only interested in that very first item. Any additional items in the IEnumerable are other elements that are also at that point but are further back in the z-order and are drawing underneath that first item. The elements further back wouldn't report themselves as the source for an input event at that point, only the topmost element would.

    Element-filtered hit testing

    Sometimes you want to know whether a specific element exists at a certain point in the UI. If so, you can specify that point for intersectingPoint and specify the element you're looking for as the subtree parameter. If the return value is not empty, that means that the element does exist at that point in the UI. If the element is the first item in the return value, that means the element is topmost in the z-order at intersectingPoint. If there are other items in the return value and subtree isn't first, the other items represent the elements rendering at intersectingPoint that are higher in z-order (visually, these render on top of the subtree element). In that case subtree is the last element in the returned IEnumerable, not the first.

    If the return value is empty, that means that the subtree element didn't exist there, at any z-order value.

    Looking for overdraw or looking at the complete visual tree

    A UI can be dynamic, especially if you're using collections from data binding for UI population. So there's occasionally a need to know which element is currently on top. You might be anticipating points in the app where the user might interact and verifying that the interactions you intend are currently possible. For this scenario, you typically specify a Point value that represents some known point such as (0,0) that is currently a valid coordinate that's within your app window. For the subtree parameter, you can pass it as null. Or you can specify subtree to be some element that you know is the root visual of a page, or is otherwise some element that you want to be the final stop for hit testing.

    Note

    If you pass null for subtree, you might see that the visual tree contains elements that aren't defined by page-level XAML, such as a Frame element and ContentPresenter. These come from the typical app initialization code that exists in most of the Microsoft Visual Studio project templates for a Windows Store app, which first creates the Frame to be the Content value. The visual tree as shown by FindElementsInHostCoordinates(Point, UIElement) methods extends all the way to Content unless you otherwise filter it with a subtree element such as a Page root.

    In the return value, you might be interested in each of the items within. So you could use foreach or similar language-specific techniques to iterate the collection and run your own logic on each of these elements. Remember that the first element in that collection is the one that is topmost in z-order.

    If you are programming using C# or Microsoft Visual Basic, the return value type of this method is projected as an IEnumerable generic collection that contains UIElement items. If you are programming using Visual C++ component extensions (C++/CX), the return type of this method is IIterable<T>.

    Examples

    This is an example utility method that determines whether an element of a given Name exists anywhere in the z-order at a Point in the UI of an app.

    private bool DoesPointContainElement(Point testPoint, string elementName, UIElement referenceFrame)
    {
        IEnumerable<UIElement> elementStack = 
          VisualTreeHelper.FindElementsInHostCoordinates(testPoint, referenceFrame);
        foreach (UIElement item in elementStack)
        {
            FrameworkElement feItem = item as FrameworkElement; 
    //cast to FrameworkElement, need the Name property
            if (feItem != null)
            {
                if (feItem.Name.Equals(elementName))
                {
                     return true;
                }
            }
         }
         // elementName was not in this stack 
         return false;
    }
    
  • FindElementsInHostCoordinates(Point, UIElement, Boolean)
    FindElementsInHostCoordinates(Point, UIElement, Boolean)
    FindElementsInHostCoordinates(Point, UIElement, Boolean)
    FindElementsInHostCoordinates(Point, UIElement, Boolean)

    Retrieves a set of objects that are located within a specified x-y coordinate point of an app UI. The set of objects represents the components of a visual tree that share that point.

    public static IIterable<UIElement> FindElementsInHostCoordinates(Point intersectingPoint, UIElement subtree, Boolean includeAllElements)public static IIterable<UIElement> FindElementsInHostCoordinates(Point intersectingPoint, UIElement subtree, Boolean includeAllElements)Public Static Function FindElementsInHostCoordinates(intersectingPoint As Point, subtree As UIElement, includeAllElements As Boolean) As IIterable( Of UIElement )public static IIterable<UIElement> FindElementsInHostCoordinates(Point intersectingPoint, UIElement subtree, Boolean includeAllElements)

    Parameters

    • intersectingPoint

      The point to use as the determination point. This point is using the coordinate space of the app window, not of any specific element (and not of subtree if specified).

    • subtree

      An object to search for. If the subtree object exists in the overall set of elements that exist at the specified intersectingPoint coordinates, then the return value contains only the subtree object and any objects that have a higher z-order than subtree, listed by inverse of z-order. If the subtree object doesn't exist at intersectingPoint coordinates, the return value will be empty.

    • includeAllElements
      System.Boolean
      System.Boolean
      System.Boolean

      true to include all elements that intersect, including those elements considered to be invisible to hit testing. false to find only visible, hit-testable elements. The default is false.

    Returns

    • An enumerable set of UIElement objects that are determined to be located in the visual tree composition at the specified point, listed by inverse of z-order.

    Remarks

    An element is considered hit-testable if it both occupies space in the layout and "produces ink". For elements that have a Brush, any non-null Brush is considered something that produces ink, even if the Brush doesn't produce visible pixels. For example, a SolidColorBrush with it's color set to Transparent still produces ink. Only a null brush does not produce ink. The Opacity property is not considered. The element still produces ink even if it's Opacity is 0.

    When the includeAllElements parameter is set to true, elements that don't produce ink are considered for hit-testing. In this case, as long as the element meets the spatial requirements (the point intersects the element bounds), then it and its ancestors are included in the results.

    Note

    Some special elements, like SwapChainPanel and MediaElement, don’t have a brush but can still produce ink.

    Examples

    Given this XAML UI:

    <Canvas Name="canvas">
      <Rectangle Name="outermost" Fill="Red" Width="200" Height="200"/>
      <Rectangle Canvas.Left="40" Canvas.Top="40" Name="hidden" Fill="Green" Width="120" Height="120"/>
      <Rectangle Canvas.Left="40" Canvas.Top="40" Name="shown" Fill="Orange" Width="120" Height="120"/>
      <Rectangle Canvas.Left="80" Canvas.Top="80" Name="center" Fill="Yellow" Width="40" Height="40"/>
      <Rectangle Canvas.Left="190" Canvas.Top="190" Name="bottomright" Fill="Pink" Width="10" Height="10"/>
    </Canvas>
    

    Here are some example usages and results from FindElementsInHostCoordinates(Point, UIElement, Boolean), using different subtree values:

    private void Test(object sender, RoutedEventArgs e)
    {
        IEnumerable<UIElement> hits;
        hits =  VisualTreeHelper.FindElementsInHostCoordinates(
          new Point(100,100), canvas, true);
        foreach (UIElement element in hits)
        {
            //run logic here, such as log the results 
        }
    // results in the following set of elements, listed by Name:
    // center - the element that is topmost in z-order at 100,100
    // shown - also renders at 100,100 but is underneath 'center'
    // hidden - is entirely underneath 'shown', 
    //   and lower in z-order because 'hidden' declared before 'shown' in XAML
    // outermost - draws under all the above at 100,100
    // canvas - the 'subtree' value, so that's the last element reported
    
        hits = VisualTreeHelper.FindElementsInHostCoordinates(
          new Point(100, 100), center, true);
        foreach (UIElement element in hits) {
            //run logic here, such as log the results
        }
    // results in 'center', because it is 'subtree' and also topmost
    
        hits = VisualTreeHelper.FindElementsInHostCoordinates(
          new Point(100, 100), bottomright, true);
    // results in an empty set, 'bottomright' doesn't render at 100,100
    }
    
  • FindElementsInHostCoordinates(Rect, UIElement)
    FindElementsInHostCoordinates(Rect, UIElement)
    FindElementsInHostCoordinates(Rect, UIElement)
    FindElementsInHostCoordinates(Rect, UIElement)

    Retrieves a set of objects that are located within a specified Rect frame of an app UI. The set of objects represents the components of a visual tree that share a rectangular area, and might include elements that overdraw.

    public static IIterable<UIElement> FindElementsInHostCoordinates(Rect intersectingRect, UIElement subtree)public static IIterable<UIElement> FindElementsInHostCoordinates(Rect intersectingRect, UIElement subtree)Public Static Function FindElementsInHostCoordinates(intersectingRect As Rect, subtree As UIElement) As IIterable( Of UIElement )public static IIterable<UIElement> FindElementsInHostCoordinates(Rect intersectingRect, UIElement subtree)

    Parameters

    • intersectingRect

      The Rect to use as the determination area. This frame is using the coordinate space of the app window, not of any specific element (and not of subtree if specified).

    • subtree

      An object to search for. If the subtree object exists in the overall set of elements that exist within the specified intersectingRect, then the return value contains only the subtree object and elements that are drawing on top of its space. If the subtree object doesn't exist within the intersectingRect frame, the return value will be empty.

    Returns

    • An enumerable set of UIElement objects that are in the visual tree composition in the specified Rect frame.

    Remarks

    The return value is not a single element, it is a collection. The collection can have more than one element because there can be multiple UI elements stacked over each other in a z-order, and also multiple elements fully or partially in the intersectingRect frame. The conventional hit-testing techniques exposed by the input event handlers, such as the sender value for a PointerPressed event, only account for the topmost element that has the highest z-order. FindElementsInHostCoordinates(Point, UIElement) methods return the whole stack of elements that share that point or area in the app UI, listed by visual tree order (which is usually the same as inverse of XAML declaration order). Using FindElementsInHostCoordinates(Point, UIElement) can thus be useful for examining cases where you've intentionally or unintentionally stacked elements. You may want to correct the order for rendering and hit-testing, or examine that order for other reasons.

    FindElementsInHostCoordinates(Point, UIElement) over an area is useful for two scenarios: basic hit testing and hit testing that is filtering for a specific element.

    Basic hit testing

    For basic hit testing, the goal is to discover which element is highest in the z-order of an app UI. If you are hit-testing for a mouse interaction you might use a point, but for touch-oriented hit testing it's often appropriate to use a rectangular area. You might have hit testing scenarios where you want to know what element exists at the top z-order before any touch event takes place. Or you might have a point that you want to expand to be a rectangle to see what's near a center point and which element might be the intended target.

    For this scenario, you should pass the rectangle you're interested in hit-testing as the value of the intersectingRect parameter. For the subtree parameter, you can pass it as null. Or you can specify subtree to be some element that you know is the root visual of a page, or is otherwise some element that you want to be the final stop for hit testing.

    The order of element in the returned IEnumerable of UIElement items is accounting for both coordinate space in the area and for the z-order. So it's possible to get hits for items that are not at the highest z-order and therefore couldn't be the source of input events. To make sure, you can do an element-filtered hit test for any items from the returned list that you're interested in, using the same intersectingRect but passing the element of interest as subtree.

    Element-filtered hit testing

    Sometimes you want to know whether a specific element exists within an area of the UI. If so, you can specify that area for intersectingRect and specify the element you're looking for as the subtree parameter. If the return value is not empty, that means that the element exists somewhere in that area. When you're hit-testing an area, the order in the return set isn't as useful for determining z-order because the set includes elements at more than one x-y coordinate. The set has a mix of elements drawing at various x-y coordinates and also elements that might be fully or partially overdrawn. To really examine an overdraw situation, use the overloads of FindElementsInHostCoordinates(Point, UIElement) that use a Point, so that the x-y coordinates and the visual tree order are no longer a factor. See FindElementsInHostCoordinates(Point, UIElement).

    If the return value is empty, that means that the subtree element didn't exist in the area.

    If you are programming using C# or Microsoft Visual Basic, the return value type of this method is projected as an IEnumerable generic collection that contains UIElement items. If you are programming using Visual C++ component extensions (C++/CX), the return type of this method is IIterable<T>.

    Examples

    Given this XAML UI:

    <Canvas Name="canvas">
      <Rectangle Name="outermost" Fill="Red" Width="200" Height="200"/>
      <Rectangle Canvas.Left="40" Canvas.Top="40" Name="hidden" Fill="Green" Width="120" Height="120"/>
      <Rectangle Canvas.Left="40" Canvas.Top="40" Name="shown" Fill="Orange" Width="120" Height="120"/>
      <Rectangle Canvas.Left="80" Canvas.Top="80" Name="center" Fill="Yellow" Width="40" Height="40"/>
      <Rectangle Canvas.Left="190" Canvas.Top="190" Name="bottomright" Fill="Pink" Width="10" Height="10"/>
    </Canvas>
    

    Here are some example usages and results from FindElementsInHostCoordinates(Rect, UIElement), using different subtree values:

    private void Test(object sender, RoutedEventArgs e)
    {
        IEnumerable<UIElement> hits;
        hits =  VisualTreeHelper.FindElementsInHostCoordinates(
          new Rect(75,75,50,50), canvas);
        foreach (UIElement element in hits)
        {
            //run logic here, such as log the results 
        }
    // results in the following set of elements, listed by Name:
    // center - the last declared XAML element is first returned, if within the area
    // shown - renders, underneath 'center' in part of the area but visible on the edges
    // hidden - entirely under 'shown', not visible but part of the area, an overdraw
    // outermost - draws under all the above
    // canvas - the 'subtree' value, and the last element reported
    
        hits = VisualTreeHelper.FindElementsInHostCoordinates(
          new Rect(75,75,50,50), center);
        foreach (UIElement element in hits) {
            //run logic here, such as log the results
        }
    // results in only 'center', because it was 'subtree' and it's also topmost
    
        hits = VisualTreeHelper.FindElementsInHostCoordinates(
          new Rect(75,75,50,50), bottomright);
    // results in an empty set, 'bottomright' isn't in the specified rect
    }
    
  • FindElementsInHostCoordinates(Rect, UIElement, Boolean)
    FindElementsInHostCoordinates(Rect, UIElement, Boolean)
    FindElementsInHostCoordinates(Rect, UIElement, Boolean)
    FindElementsInHostCoordinates(Rect, UIElement, Boolean)

    Retrieves a set of objects that are located within a specified Rect frame of an app UI. The set of objects represents the components of a visual tree that share a rectangular area, and might include elements that overdraw.

    public static IIterable<UIElement> FindElementsInHostCoordinates(Rect intersectingRect, UIElement subtree, Boolean includeAllElements)public static IIterable<UIElement> FindElementsInHostCoordinates(Rect intersectingRect, UIElement subtree, Boolean includeAllElements)Public Static Function FindElementsInHostCoordinates(intersectingRect As Rect, subtree As UIElement, includeAllElements As Boolean) As IIterable( Of UIElement )public static IIterable<UIElement> FindElementsInHostCoordinates(Rect intersectingRect, UIElement subtree, Boolean includeAllElements)

    Parameters

    • intersectingRect

      The Rect to use as the determination area. This frame is using the coordinate space of the app window, not of any specific element (and not of subtree if specified).

    • subtree

      An object to search for. If the subtree object exists in the overall set of elements that exist within the specified intersectingRect, then the return value contains only the subtree object and elements that are drawing on top of its space. If the subtree object doesn't exist within the intersectingRect frame, the return value will be empty.

    • includeAllElements
      System.Boolean
      System.Boolean
      System.Boolean

      true to include all elements that intersect, including those elements considered to be invisible to hit testing. false to find only visible, hit-testable elements. The default is false.

    Returns

    • An enumerable set of UIElement objects that are determined to be located in the visual tree composition in the specified Rect frame.

    Remarks

    An element is considered hit-testable if it both occupies space in the layout and "produces ink". For elements that have a Brush, any non-null Brush is considered something that produces ink, even if the Brush doesn't produce visible pixels. For example, a SolidColorBrush with it's color set to Transparent still produces ink. Only a null brush does not produce ink. The Opacity property is not considered. The element still produces ink even if it's Opacity is 0.

    When the includeAllElements parameter is set to true, elements that don't produce ink are considered for hit-testing. In this case, as long as the element meets the spatial requirements (the rect intersects the element bounds), then it and its ancestors are included in the results.

    Note

    Some special elements, like SwapChainPanel and MediaElement, don’t have a brush but can still produce ink.

    Examples

    Given this XAML UI:

    <Canvas Name="canvas">
      <Rectangle Name="outermost" Fill="Red" Width="200" Height="200"/>
      <Rectangle Canvas.Left="40" Canvas.Top="40" Name="hidden" Fill="Green" Width="120" Height="120"/>
      <Rectangle Canvas.Left="40" Canvas.Top="40" Name="shown" Fill="Orange" Width="120" Height="120"/>
      <Rectangle Canvas.Left="80" Canvas.Top="80" Name="center" Fill="Yellow" Width="40" Height="40"/>
      <Rectangle Canvas.Left="190" Canvas.Top="190" Name="bottomright" Fill="Pink" Width="10" Height="10"/>
    </Canvas>
    

    Here are some example usages and results from FindElementsInHostCoordinates(Rect, UIElement), using different subtree values:

    private void Test(object sender, RoutedEventArgs e)
    {
        IEnumerable<UIElement> hits;
        hits =  VisualTreeHelper.FindElementsInHostCoordinates(
          new Rect(75,75,50,50), canvas, true);
        foreach (UIElement element in hits)
        {
            //run logic here, such as log the results 
        }
    // results in the following set of elements, listed by Name:
    // center - the last declared XAML element is first returned, if within the area
    // shown - renders, underneath 'center' in part of the area but visible on the edges
    // hidden - entirely under 'shown', not visible but part of the area, an overdraw
    // outermost - draws under all the above
    // canvas - the 'subtree' value, and the last element reported
    
        hits = VisualTreeHelper.FindElementsInHostCoordinates(
          new Rect(75,75,50,50), center, true);
        foreach (UIElement element in hits) {
            //run logic here, such as log the results
        }
    // results in only 'center', because it was 'subtree' and it's also topmost
    
        hits = VisualTreeHelper.FindElementsInHostCoordinates(
          new Rect(75,75,50,50), bottomright, true);
    // results in an empty set, 'bottomright' isn't in the specified rect
    }
    
  • GetChild(DependencyObject, Int32)
    GetChild(DependencyObject, Int32)
    GetChild(DependencyObject, Int32)
    GetChild(DependencyObject, Int32)

    Using the provided index, obtains a specific child object of the provided object by examining the visual tree.

    public static DependencyObject GetChild(DependencyObject reference, Int32 childIndex)public static DependencyObject GetChild(DependencyObject reference, Int32 childIndex)Public Static Function GetChild(reference As DependencyObject, childIndex As Int32) As DependencyObjectpublic static DependencyObject GetChild(DependencyObject reference, Int32 childIndex)

    Parameters

    Returns

    Remarks

    Examples

    Here's an example of a utility function that can copy a list of child elements of a particular type from within a visual tree. It uses the basic traversal methods GetChildrenCount(DependencyObject) and GetChild(DependencyObject, Int32). It uses recursion so that elements can be found no matter what level of nesting within intermediate containers exists. It also uses an IsSubclassOf extension method from System.Reflection that extends the type comparison to consider subtypes as a match for a Type.

    internal static void FindChildren<T>(List<T> results, DependencyObject startNode)
      where T : DependencyObject
    {
        int count = VisualTreeHelper.GetChildrenCount(startNode);
        for (int i = 0; i < count; i++)
        {
            DependencyObject current = VisualTreeHelper.GetChild(startNode, i);
            if ((current.GetType()).Equals(typeof(T)) || (current.GetType().GetTypeInfo().IsSubclassOf(typeof(T))))
            {
                T asType = (T)current;
                results.Add(asType);
            }
            FindChildren<T>(results, current);
        }
    }
    
  • GetChildrenCount(DependencyObject)
    GetChildrenCount(DependencyObject)
    GetChildrenCount(DependencyObject)
    GetChildrenCount(DependencyObject)

    Returns the number of children that exist in an object's child collection in the visual tree.

    public static int GetChildrenCount(DependencyObject reference)public static int GetChildrenCount(DependencyObject reference)Public Static Function GetChildrenCount(reference As DependencyObject) As intpublic static int GetChildrenCount(DependencyObject reference)

    Parameters

    Returns

    • int
      int
      int

      The number of visual children for the provided source visual.

    Remarks

    Examples

    Here's an example of a utility function that can copy a list of child elements of a particular type from within a visual tree. It uses the basic traversal methods GetChildrenCount(DependencyObject) and GetChild(DependencyObject, Int32). It uses recursion so that elements can be found no matter what level of nesting within intermediate containers exists. It also uses an IsSubclassOf extension method from System.Reflection that extends the type comparison to consider subtypes as a match for a Type.

    internal static void FindChildren<T>(List<T> results, DependencyObject startNode)
      where T : DependencyObject
    {
        int count = VisualTreeHelper.GetChildrenCount(startNode);
        for (int i = 0; i < count; i++)
        {
            DependencyObject current = VisualTreeHelper.GetChild(startNode, i);
            if ((current.GetType()).Equals(typeof(T)) || (current.GetType().GetTypeInfo().IsSubclassOf(typeof(T))))
            {
                T asType = (T)current;
                results.Add(asType);
            }
            FindChildren<T>(results, current);
        }
    }
    
  • GetOpenPopups(Window)
    GetOpenPopups(Window)
    GetOpenPopups(Window)
    GetOpenPopups(Window)

    Retrieves a collection of all open popup controls from the target Window.

    public static IVectorView<Popup> GetOpenPopups(Window window)public static IVectorView<Popup> GetOpenPopups(Window window)Public Static Function GetOpenPopups(window As Window) As IVectorView( Of Popup )public static IVectorView<Popup> GetOpenPopups(Window window)

    Parameters

    Returns

    • The list of all open popups. If no popups are open, the list is empty.

    Remarks

    Popups don't exist in the conventional XAML visual tree that begins from the root visual, although they are associated with the app main window. Unless your app maintains a list of all the Popup elements you've created as well as a status (the IsOpen value), it can be difficult to keep track of them. Sometimes you will want to clear all popups prior to initiating another UI action, like navigating the page or displaying a flyout. GetOpenPopups(Window) provides the utility so that you can get a reference to all these popups as Popup instances, and then you would typically set IsOpen to false on each of them.

    Elements such as AppBar are not considered a popup, they are owned by the Page. A ToolTip is also not considered a popup, it's considered a child of the element that uses the ToolTipService attached properties to host it. Both AppBar and ToolTip elements are thus in the conventional XAML visual tree, even if they're not always displayed at the time. You could find these with GetChild(DependencyObject, Int32) or other VisualTreeHelper API, or by walking the tree with Child/Items/Children and related properties if you know the exact structure by type.

  • GetParent(DependencyObject)
    GetParent(DependencyObject)
    GetParent(DependencyObject)
    GetParent(DependencyObject)

    Returns an object's parent object in the visual tree.

    public static DependencyObject GetParent(DependencyObject reference)public static DependencyObject GetParent(DependencyObject reference)Public Static Function GetParent(reference As DependencyObject) As DependencyObjectpublic static DependencyObject GetParent(DependencyObject reference)

    Parameters

    Returns

Device family

Windows 10 (introduced v10.0.10240.0)

API contract

Windows.Foundation.UniversalApiContract (introduced v1)

Attributes

Windows.Foundation.Metadata.ContractVersionAttribute
Windows.Foundation.Metadata.MarshalingBehaviorAttribute
Windows.Foundation.Metadata.StaticAttribute
Windows.Foundation.Metadata.StaticAttribute
Windows.Foundation.Metadata.ThreadingAttribute
Windows.Foundation.Metadata.WebHostHiddenAttribute

Details

Assembly

Windows.UI.Xaml.Media.dll