How to find the visual parent or child element using VisualTreeHelper in WPF

No.of Views6979
Bookmarked0 times
Downloads 
Votes0
By  Prabu   On  03 Jul 2010 03:07:44
Tag : WPF , Miscellaneous
How to find the visual parent or child element using VisualTreeHelper in WPF
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

In this article ,i will describe how to find the parent object or control in WPF using VisualTreeHelper.The VisualTreeHelper is very useful class which help us to find or drill-down element from the hosted container.

The following method will help you to find the visual parent element from the container.

public static T FindVisualParent<T>(UIElement element) where T : UIElement
    {
        UIElement parent = element;while (parent != null)
        {
            T correctlyTyped = parent as T;if (correctlyTyped != null)
            {return correctlyTyped;
            }
            parent = VisualTreeHelper.GetParent(parent) as UIElement;
        }return null;
    }

The following method will help you to find the child element from the container.

public static T FindChild<T>(DependencyObject parent)where T : DependencyObject
    {if (parent == null) return null;

        T childElement = null;int childrenCount = VisualTreeHelper.GetChildrenCount(parent);for (int i = 0; i < childrenCount; i++)
        {
            var child = VisualTreeHelper.GetChild(parent, i);
            T childType = child as T;if (childType == null)
            {
                childElement = FindChild<T>(child);if (childElement != null) break;
            }else{
                childElement = (T)child;break;
            }
        }return childElement;
    }

 That's all, i hope this is help to you.

 
Sign Up to vote for this article
 
About Author
 
Prabu
Occupation-Software Engineer
Company-
Member Type-Fresh
Location-India
Joined date-23 Jun 2010
Home Page-
Blog Page-http://prabu-guru.blogspot.com/
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top