RSS

Find control inside silverlight

06 Feb

There is no other way to finding a control inside a Silverlight page or controls. You need to traverse the container (Grid) element. this is a generic function that can find any type of control in side a container(Grid) control using recursion.

public T FindControl(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(child, targetType, ControlName) != null)
{
result = FindControl(child, targetType, ControlName);
break;
}
}
return result;
}

 

 

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

 

how to call this function like here
TextBlock ControlToSearch = FindControl<TextBlock>((UIElement)ContainerControl, typeof(TextBlock), “NameOfTheControl”);

or

for (int k = 1; k <= TotalCountCbo; k++) {

RadComboBox ControlToSearch = FindControl<RadComboBox>((UIElement)myGrid, typeof(RadComboBox), “cboname” + k);

}

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

 
Leave a comment

Posted by on February 6, 2012 in Silverlight

 

Tags: , , , , , ,

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.