在上面的XAML代码中,我正在使用下面的代码来获取(ItemsCotnrol x:Name =“PointsList)的子级,并获得count =0。您能帮我解决此问题吗?
int count = VisualTreeHelper.GetChildrenCount(pointsList);
if (count > 0)
{
for (int i = 0; i < count; i++)
{
UIElement child = VisualTreeHelper.GetChild(pointsList, i) as UIElement;
if (child.GetType() == typeof(TextBlock))
{
textPoints = child as TextBlock;
break;
}
}
}
pointsList定义如下。
pointsList = (ItemsControl)GetTemplateChild("PointsList");
最佳答案
当您在后面的代码中使用myPoints时,可以使用ItemContainerGenerator GetContainerForItem。只需传递您的物品之一即可获得容器。
使用辅助方法GetChild获取每个项目的文本块的代码:
for (int i = 0; i < PointsList.Items.Count; i++)
{
// Note this part is only working for controls where all items are loaded
// and generated. You can check that with ItemContainerGenerator.Status
// If you are planning to use VirtualizingStackPanel make sure this
// part of code will be only executed on generated items.
var container = PointsList.ItemContainerGenerator.ContainerFromIndex(i);
TextBlock t = GetChild<TextBlock>(container);
}
从DependencyObject获取子对象的方法:
public T GetChild<T>(DependencyObject obj) where T : DependencyObject
{
DependencyObject child = null;
for (Int32 i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
child = VisualTreeHelper.GetChild(obj, i);
if (child != null && child.GetType() == typeof(T))
{
break;
}
else if (child != null)
{
child = GetChild<T>(child);
if (child != null && child.GetType() == typeof(T))
{
break;
}
}
}
return child as T;
}