Home Articles Windows presentation foundation VisualTreeHelper Class in wpf

Tips and tricks

Site statistics

Members : 19
Content : 104
Content View Hits : 18411

Who's Online

We have 308 guests online
VisualTreeHelper Class in wpf PDF Print E-mail
User Rating: / 0
PoorBest 
Articles - Windows presentation foundation
Written by Dot4Pro   
Wednesday, 11 November 2009 03:14

One nice use of VisualTreeHelper class 

VisualTreeHelper class provides utility members that provide common tasks regarding nodes in the visual tree like finding childs, parents,sbilings etc.  This class cannot be created directly in xaml.

 

Following example code shows you how to find the first child object of a certain type for eg: Find the ScrollViewer visual node on the listbox controls

C# code
-----------------------------

public static TItem FindVisualChild<TItem>(DependencyObject obj) where TItem : DependencyObject

        {  

            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)

            {

                var child = VisualTreeHelper.GetChild(obj, i);

                if (child != null && child is TItem)

                    return (TItem)child;

                var childOfChild = FindVisualChild<TItem>(child);

                if (childOfChild != null)

                {

                    return childOfChild;

                }

            }

            return null;

        }

Use this class like this:

ScrollViewer scrollViewer = VisualHelper.FindVisualChild<ScrollViewer>(listbox);

 

 

 

Add comment


Security code
Refresh

feed-image Feed Entries