Tuesday, May 29, 2012

Find Child Control from ControlTemplate in Silverlight

In Silverlight application development sometimes you need to find ControlTemplates Child control from silverlight control.

Below is code that will return child control from TemplateChild of passed parent DependencyObject.

 public static FrameworkElement GetTemplateChildByName
       (DependencyObject parent, string name)
    int childnum = VisualTreeHelper.GetChildrenCount(parent);
    for (int i = 0; i < childnum; i++)
        var child = VisualTreeHelper.GetChild(parent, i);
        if (child is FrameworkElement && 
                ((FrameworkElement)child).Name == name)
           return child as FrameworkElement;
           var s = GetTemplateChildByName(child, name);
           if (s != null)
             return s;
    return null;

Above method will return passed named child control from parent control.

Here is the code that call GetTemplateChildByName method.

 private void TabHeaderBackgroundBorder_MouseLeftButtonUp
                (object sender, MouseButtonEventArgs e)
    FrameworkElement selectedItem = TabHeader as FrameworkElement;
    FrameworkElement TabPanel= 
           GetTemplateChildByName(selectedItem, "MyTabContentPanel");
    FrameworkElement parentBorder = 
           GetTemplateChildByName(TabPanel, "parentBorder");

In above code, I am finding ScalePanel from TabHeader Items and finding Border within ScalePanel.

so yon can find Hierarchy of control from parent control.

No comments:

Post a Comment