Sunday, September 18, 2011

Finding a child element in silverlight

Today I am going to share a simple code that will help us to find a child element from a silverlight control. In one of our control we had a requirement to find out the internal scrollviewer, by default we didn't had support to find the internal element right way.

So the only way is to try finding it with VisualTreeHelper. And do a recursive call to find out if the Element With the name exists or not. we can use couple of modification depending ton Name or Type, bellow I have shared a Extension method which demonstrate the idea.

public static class FrameworkElementExtensions
    {
        public static FrameworkElement FindChild(this FrameworkElement element, string targetName)
        {
            if (element == null || string.IsNullOrEmpty(targetName))
                return null;
            if (element.Name == targetName)
                return element;
            for (int index = 0; index < VisualTreeHelper.GetChildrenCount(element); index++)
            {
                var child = (FrameworkElement)VisualTreeHelper.GetChild(element, index);
                if (child.Name == targetName)
                    return child;
                child = FindChild(child, targetName);
                if (child != null)
                    return child;
            }
            return null;
        }

        public static object TryFindResource(this FrameworkElement element, object resourceKey)
        {
            var currentElement = element;

            while (currentElement != null)
            {
                var resource = currentElement.Resources[resourceKey];
                if (resource != null)
                {
                    return resource;
                }

                currentElement = currentElement.Parent as FrameworkElement;
            }

            return Application.Current.Resources[resourceKey];
        }


No comments:

Post a Comment