Fetching Kids ItemsControl

In the above XAML code, I get the children (from ItemsCotnrol x: Name = "PointsList) using the code below and getting count = 0. Help me fix this problem.

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"); 
+4
source share
1 answer

When you use myPoints in your code, you can use ItemContainerGenerator GetContainerForItem. Just pass one of your items to get a container for it.

Code to get a text block for each element using the GetChild helper method:

 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 to get the child 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; } 
+3
source

Source: https://habr.com/ru/post/1336884/


All Articles