6

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"); 
codematrix
  • 1,571
  • 11
  • 35
  • 53
  • 1
    It is not a good practise to work with ItemsControl's content using trees. So what do you want to do with TextBoxes? – Marat Khasanov Jan 25 '11 at 07:13
  • I want to capture mouse events for the TextBlock. Is there a way? Please let me know. – codematrix Jan 25 '11 at 21:43
  • Just hook the mouse events at the ItemsControl level and let the events bubble. – Joe White Jan 26 '11 at 23:53
  • Does this answer your question? [How do I access the children of an ItemsControl?](https://stackoverflow.com/questions/1000345/how-do-i-access-the-children-of-an-itemscontrol) – StayOnTarget Apr 22 '20 at 12:36

1 Answers1

4

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;
 }
bartosz.lipinski
  • 2,627
  • 2
  • 21
  • 34