I want to get all the UI-items from an ItemsControl.
From this post How do I access the children of an ItemsControl? I copied an answer and it works so far.
However, if I DIRECTLY execute the code in the for-loop after setting the ItemsSource (like in the bottom example), the contentpresenter is null and I cannot work with it.
If I run the for-loop quite a while later (maybe when I hit a button), everything works out fine.
How can I access all Children of a ItemsControl, DIRECTLY after setting the ItemsSource?
itemscontrol.ItemsSource = items; // items is a list
itemscontrol.ApplyTemplate(); // might refresh the itemscontrol
for (int i = 0; i < itemscontrol.Items.Count; i++)
{
// ↓ this is null
ContentPresenter contentpresenter = (ContentPresenter)itemscontrol.ItemContainerGenerator.ContainerFromItem(itemscontrol.Items[i]);
// ↑ this is null
contentpresenter.ApplyTemplate();
StackPanel stackPanel = (StackPanel)contentpresenter.ContentTemplate.FindName("selectedStackpanel", contentpresenter);
// do some stuff with the stackpanel
}
The better solution is to add related attributes to your item model e.g. a
IsUserSelectedproperty. Then create aStyle, which you assign toItemsControl.ItemContainerStyle. Inside thisStyleyou define a trigger that triggers onIsUserSelected.That's how it is done. Don't deal with the generator and check if each item is generated. Let the framework do this work for you.
Since you already have a property
HighlightIdin your code-behind file, you can use aIMultiValueConvertertogether with aMultiBindingto define a color based on the value:MainWindow.xaml.cs
HighlightIdToBrushConverter.cs
MainWindow.xaml