Click here to Skip to main content
13,148,058 members (87,541 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

15.3K views
3 bookmarked
Posted 26 Apr 2010

Walk up the Visual Tree

, 26 Nov 2010
Rate this:
Please Sign up or sign in to vote.
Introduction The following snippet provides a generic method to walk up the visual tree of Silverlight in order to find an element of a given type. It will return the first found item of said type, or null if the search ends at the visual tree root without any results.  Code // walk up the...

Introduction


The following snippet provides a generic method to walk up the visual tree of Silverlight in order to find an element of a given type. It will return the first found item of said type, or null if the search ends at the visual tree root without any results.  


Code


// walk up the visual tree to find object of type T, starting from initial object
public static T FindUpVisualTree<T>(DependencyObject initial) where T : DependencyObject
{
    DependencyObject current = initial;
 
    while (current != null && current.GetType() != typeof(T))
    {
         current = VisualTreeHelper.GetParent(current);
    }
    return current as T;   
}

Usage 


Find the first Grid containing the Button (x:Name="button01"), regardless if the Button is located directly in a Grid or nested within some other containers.   



Grid gridContainingButton = FindUpVisualTree<Grid>(button01);

References  


Understanding the Visual
Tree and Logical Tree in WPF
by Josh Smith

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Mike Fuchs
Software Developer Glaux Soft AG, Bern
Switzerland Switzerland
MS in Physics
Secondary School Teacher
Software Developer / Project Manager

You may also be interested in...

Comments and Discussions

 
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.170915.1 | Last Updated 26 Nov 2010
Article Copyright 2010 by Mike Fuchs
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid