Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving children of ItemsControl

In the above XAML code, I am getting children (of ItemsCotnrol x:Name="PointsList) using below code and getting the count = 0. Can you help me to fix this issue.

        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 is defined as follows.

pointsList = (ItemsControl)GetTemplateChild("PointsList"); 
like image 835
codematrix Avatar asked Oct 14 '22 17:10

codematrix


1 Answers

As you are using myPoints in your code behind you can use ItemContainerGenerator GetContainerForItem. Just pass one of yours items to get container for it.

Code for getting textblock for each item with helper method 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);
}

Method for getting child object from 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;
 }
like image 63
bartosz.lipinski Avatar answered Oct 25 '22 11:10

bartosz.lipinski