Извлечение детей ItemsControl - PullRequest
4 голосов
/ 25 января 2011

В приведенном выше коде XAML я получаю детей (из ItemsCotnrol 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 Ответ

3 голосов
/ 25 января 2011

Поскольку вы используете 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;
 }
...