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.

Advertisements
 
Leave a comment

Posted by on February 6, 2012 in Silverlight

 

Tags: , , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: