I have created ItemsControl:
<ItemsControl x:Name="myItemsControl">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock x:Name="myTextBlock" Text="{Binding Name}" Width="75" Height="75" Margin="10" Background="Black" Foreground="White"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
When I set ItemSource and get ContentPresenter same time, it gives me error System.InvalidOperationException: 'This operation is valid only on elements that have this template applied.'
myItemsControl.ItemsSource = new List<Person>() {
new Person { Name = "1.Name?" },
new Person { Name = "2.Name?" },
new Person { Name = "3.Name?" },
new Person { Name = "4.Name?" },
new Person { Name = "5.Name?" },
}; ;
for ( int i = 0; i < myItemsControl.Items.Count; i++ ) {
ContentPresenter contentPresenter = ( ContentPresenter ) myItemsControl.ItemContainerGenerator.ContainerFromItem(myItemsControl.Items[i]);
TextBlock textBlock = contentPresenter.ContentTemplate.FindName("myTextBlock", contentPresenter) as TextBlock;
}
I know that after the "ItemControl" is fully updated, I need to get the "contentpresser". But I don't know how to do this?
You can access the ContentPresenter in the Loaded event for ItemsControl
Like this