检索ItemsControl的子项

6
在上面的XAML代码中,我使用以下代码获取ItemsControl x:Name="PointsList"的子元素,并且获取到的数量为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"); 

1
使用树来处理ItemsControl的内容并不是一个好的做法。那么你想用TextBoxes做什么? - Marat Khasanov
我想捕获TextBlock的鼠标事件。有什么方法吗?请告诉我。 - codematrix
只需在ItemsControl级别挂钩鼠标事件,让事件冒泡即可。 - Joe White
这回答解决了你的问题吗?如何访问ItemsControl的子元素? - StayOnTarget
1个回答

4

如果您在代码后台使用myPoints,则可以使用ItemContainerGeneratorGetContainerForItem。只需将其中一个项目传递给它即可获取其容器。

使用辅助方法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;
 }

@baalazamon,谢谢,我总是忘记“..ItemContainerGenerator.ContainerFromIndex(i)” - denis morozov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接