Saturday, September 18, 2010

Find control inside silverlight container controls

There is no standard API for finding a control inside a Silverlight page or container control like we have in ASP.NET. You need to traverse the container element using VisualTreeHelper. Here is a generic function that can find any type of control in side a container control using recursion.

public T FindControl<T>(UIElement parent, Type targetType, string ControlName) where T : FrameworkElement
        {
           
            if (parent == null) return null;

            if (parent.GetType() == targetType && ((T)parent).Name == ControlName)
            {
                return (T)parent;
            }
            T result = null;
            int count = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < count; i++)
            {
                UIElement child = (UIElement)VisualTreeHelper.GetChild(parent, i);

                if (FindControl<T>(child, targetType, ControlName) != null)
                {
                    result = FindControl<T>(child, targetType, ControlName);
                    break;
                }
            }
            return result;
        }

parent: is the container control that needs to be traversed for the desired control.
targetType: Target Control type.
ControlName: is the name/Id of the control to be searched.

Example Usage:
TextBlock ControlToSearch = FindControl<TextBlock>((UIElement)ContainerControl, typeof(TextBlock), "NameOfTheControlToSearch");

Method will return the desired control if found in container otherwise NULL.

3 comments:

  1. Hi Muhammad
    I am a newbie and thanks for the findcontrol I was struggling...Maybe you could help me with navigate uri..
    I used your find to get the frame within a page
    I would think myFrame.Navigate(new Uri("/MyPage", UriKind.Relative));.
    But I get unknown error may be problem with uri
    I have had issues getting uri to work in past any suggestions??Hope my explanation is clear.
    I can be found at bbuchanan@nspirehealth.com

    ReplyDelete
  2. Dear Muhammed,
    i want to tell you you are very good man to be want share knowledge with others
    Many Thanks to you man

    ReplyDelete
  3. Thanks Soooooooooo Much Dear.........its greeeeeeet greeeeeeet help me to find dynamic create control.
    Thanks brother.......
    i find so many article but this fantastic....

    ReplyDelete