I want to create a custom StackPanel derived from StackPanel. But to add the items, I want to create a special list (can use a List<> or ObservableCollection<>). It should be something like this,
<mc:MyStackPanel>
<mc:MyStackPanel.Items>
<mc:MyControl Content="A" />
<mc:MyControl Content="B" />
<mc:MyControl Content="C" />
</mc:MyStackPanel.Items>
</mc:MyStackPanel>
Not like this (currently this one is working),
<mc:MyStackPanel>
<mc:MyControl Content="A" />
<mc:MyControl Content="B" />
<mc:MyControl Content="C" />
</mc:MyStackPanel>
I try using the ObservableCollection and it works perfectly if I add the items. The intellisense were also showing only one MyControl that can be added.
Now, how to get the list from the collection and adds it to the StackPanel i.e. using stkPanel.Children.Add().
Should I use Panel instead or how to get the list and added to the Panel? Thanks in advance.
PS: I tried several options, but the list always null, including using ItemsControl. So probably I’m missing some points here. Again using ItemsControl doesn’t fit my scenario because I only want one control type that can be added to the panel.
How about using the collection changed event of the
ObservableCollectionto keep theChildrenproperty in sync? I’ve also included theContentPropertyattribute so you don’t have to add items explicitly to the collection in XAML, this could be removed if you wanted.The XAML then looks like this (with the local namespace pointing to the project that the custom controls are in)