如何在页面资源中找到子控件?

时间:2016-06-23 15:02:40

标签: c# xaml windows-phone-7 windows-phone-8 data-binding

我们有一个Windows手机应用程序,我们在Page.Resource中有DataTemplate。下面是xaml:

    <PhoneApplicationPage
<PhoneApplicationPage.Resources>
<DataTemplate>
<ScrollViewer> // We want to fetch this control inside DataTemplate
..
</ScrollViewer>
</DataTemplate>
</PhoneApplicationPage.Resources>

<Grid Name="LayoutRoot">
<ItemsControl ItemTemplate={StatisSource DataTemplate}>
</ItemsControl>
</Grid>

</PhoneApplicationPage

到目前为止,我们已经使用Visual Tree帮助程序并迭代来查找其中的子控件。以下是我们使用的帮助代码段:

public T FindChild<T>(DependencyObject parent, string childName)
where T : DependencyObject
    {
        // Confirm parent and childName are valid. 
        if (parent == null) return null;

        T foundChild = null;

        int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < childrenCount; i++)
        {
            var child = VisualTreeHelper.GetChild(parent, i);
            // If the child is not of the request child type child
            T childType = child as T;
            if (childType == null)
            {
                // recursively drill down the tree
                foundChild = FindChild<T>(child, childName);

                // If the child is found, break so we do not overwrite the found child. 
                if (foundChild != null) break;
            }
            else if (!string.IsNullOrEmpty(childName))
            {
                var frameworkElement = child as FrameworkElement;
                // If the child's name is set for search
                if (frameworkElement != null && frameworkElement.Name == childName)
                {
                    // if the child's name is of the request name
                    foundChild = (T)child;
                    break;
                }
            }
            else
            {
                // child element found.
                foundChild = (T)child;
                break;
            }
        }

        return foundChild;
    }

并将上述函数调用为:

                ScrollViewer scrollViewer = FindChild<ScrollViewer>((this.View.FindName("AdSlider") as ItemsControl) ,"scrollViewer") as ScrollViewer;

但scrollViewer对象始终具有空值。我们无法在datatemplate中获取预期的控件。有什么建议吗?

感谢。

1 个答案:

答案 0 :(得分:0)

1不要为您的功能提供控件名称

更改:

ScrollViewer scrollViewer = FindChild<ScrollViewer>((this.View.FindName("AdSlider") as ItemsControl) ,"scrollViewer") as ScrollViewer;

我没有在您的示例中看到任何名为AdSlider的控件。

进入:

ScrollViewer scrollViewer = FindChild<ScrollViewer>((this.View.FindName("AdSlider") as ItemsControl) , null);

2为您的DataTemplate提供名称

更改:

<DataTemplate>

进入:

<DataTemplate x:Key="dataTemplate1">

3也请更正

<ItemsControl ItemTemplate={StatisSource dataTemplate1}>

成:

<ItemsControl ItemTemplate={StaticSource dataTemplate1}>