Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding control within WPF itemscontrol

Hi i have few a single textbox within the the datatemplate for itemscontrol. When i bind the itemcontrols to a observable collection i get two text boxes. But i need to do some manipulations based on each of the text boxes for which i want to find each textbox seperatly using some id.

Can anybody help on how to find a control witin the itemscontrol in WPF.

like image 212
deepak Avatar asked Jun 11 '09 09:06

deepak


2 Answers

Using the ItemContainerGenerator you can obtain the generated container for an item and traverse the visual tree downwards to find your TextBox. In the case of an ItemsControl it will be a ContentPresenter, but a ListBox will return a ListBoxItem, ListView a ListViewItem, etc.

ContentPresenter cp = itemsControl.ItemContainerGenerator.ContainerFromItem(item) as ContentPresenter; TextBox tb = FindVisualChild<TextBox>(cp); if (tb != null) {     // do something with tb }  public static T FindVisualChild<T>(DependencyObject depObj) where T : DependencyObject {     if (depObj != null)     {         for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)         {             DependencyObject child = VisualTreeHelper.GetChild(depObj, i);             if (child != null && child is T)             {                 return (T)child;             }              T childItem = FindVisualChild<T>(child);             if (childItem != null) return childItem;         }     }     return null; } 

You can also obtain the container by index if you want by using

itemsControl.ItemContainerGenerator.ContainerFromIndex(0); 
like image 109
Bryce Kahle Avatar answered Sep 18 '22 09:09

Bryce Kahle


Thanks Bryce, I tried to tick the up arrow but it says my rating is too low! Sorry!

I amended the code to return all a list of all the children of the given type as it was what I needed and thought someone else might find it useful.

Thanks again Bryce, really helpful - sorry about the rating thing!

public static List<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject     {         List<T> list = new List<T>();         if (depObj != null)         {             for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)             {                 DependencyObject child = VisualTreeHelper.GetChild(depObj, i);                 if (child != null && child is T)                 {                     list.Add((T)child);                 }                  List<T> childItems = FindVisualChildren<T>(child);                 if (childItems != null && childItems.Count() > 0)                 {                     foreach (var item in childItems)                     {                         list.Add(item);                     }                 }             }         }         return list;     } 
like image 20
Andy Clarke Avatar answered Sep 19 '22 09:09

Andy Clarke