I have an ItemsControl defined as below
<ItemsControl Name="PlannerItemControl">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Name="MainGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200"/>
<ColumnDefinition Width="Auto" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="auto" />
</Grid.RowDefinitions>
<TextBox Name="test" ></TextBox>
...
...
...
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
In my code behind, I want to loop through all controls in an item
PlannerItemControl.ItemsSource = Plannermod.TimetableModelList;
foreach (var item in PlannerItemControl.Items)
{
ContentPresenter cp = PlannerItemControl.ItemContainerGenerator.ContainerFromItem(item) as ContentPresenter;
TextBox tb = FindVisualChild<TextBox>(cp);
if (tb != null)
{
// do something with the textbox
}
}
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;
}
The problem is the the value of cp is always null although there are items in the itemscontrol since I go inside the foreach loop. Please help