1
我们有一个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
到目前为止,我们已经使用了可视化树帮助程序,并在其中查找子控件。下面是我们所使用的辅助代码段:
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中获取预期的控件。任何建议?
谢谢。
感谢您的反馈都灵。但在完成所有建议之后,FindChild方法返回一个异常'引用不是有效的可视化依赖对象',因为它不会接受作为DataTemplate的参数。所以我们尝试了另一种方法:((this.View.FindName(“AdvertSlider”)作为SlideViewExtended).ItemTemplate.LoadContent()作为ScrollViewer)。但是这种方法创建了一个UI元素的副本,并不能帮助我们操纵ScrollViewer的滚动行为。 – prdp89
我纠正了一些对我来说显而易见的错误。但回头看后,我不确定要了解你在寻找什么。我还纠正了代码不可见的point2 –
我们试图在Itemscontrol的datatemplate中查找scrollviewer,我们的任务是滚动scrollviewer。 – prdp89