If you are working on a Silverlight application, it's very imperative that you will end up wanting to assess a control from a design template.
Let's say I have a template where a CheckBox control is defined and if I want to access this control in my code behind, there is no direct way to do it.
You can get the reference of the control searching against its name.
Let's say I have a template where a CheckBox control is defined and if I want to access this control in my code behind, there is no direct way to do it.
The following method will recursively look for this control hiding anywhere in the control template against its name and return it when found.... <ControlTemplate ..> <Grid>... <CheckBox x:Name="chkAll" .../> </Grid> </ControlTemplate /> ...
private object GetChildControl( DependencyObject parent, string name)
{
Object control = null ;
int count = VisualTreeHelper.GetChildrenCount(parent);
for (int counter = 0; counter < count; counter++)
{
control = VisualTreeHelper.GetChild(parent, counter);
//name supplied then Return Control if the control name matches
if ((control as DependencyObject).GetValue(NameProperty).ToString() == name)
return control;
else //Search Recursively if not found
{
control = GetChildControl(control as DependencyObject, name);
if (control != null )
return control;
}
}
return null ;
}
You can get the reference of the control searching against its name.
CheckBox checkBox = (CheckBox)GetChildControl(this,"chkAll");
Comments
Post a Comment