如何在silverlight 4中找到一种风格的儿童控件?

时间:2010-02-26 06:44:50

标签: silverlight

您好我有ContentControl,我正在应用我有ListBox的样式。我想在Xaml.cs中找到ListBoxItem。

1 个答案:

答案 0 :(得分:1)

我找到了解决方案。我已经实现了一个方法来查找带有两个参数的视觉元素,需要找到父元素和控件类型。在调用此方法之前,我使用了ApplyTemplate方法

public static FrameworkElement[] FindDownInTree(FrameworkElement parent, Type controlType)
{
    List<FrameworkElement> lst = new List<FrameworkElement>();

    FindDownInTree(lst, parent, controlType);

    if (lst.Count > 0)
        return lst.ToArray();

    return null;
}



private static void FindDownInTree(List<FrameworkElement> lstElem, DependencyObject parent, Type controlType)
{

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
    {
        DependencyObject visual = VisualTreeHelper.GetChild(parent, i);

        if (controlType.IsInstanceOfType(visual))
        {
            lstElem.Add(visual as FrameworkElement);
        }

        if (visual != null)
        {
            FindDownInTree(lstElem, visual, controlType);
        }

    }
}