I have created a custom panel (MyCustomControl) that can contain other controls and be configurable through dependency properties. Inside a different user control (MyUserControl), I have multiple instances of MyCustomControl configured in XAML.
Outside of the user control, I am trying to bind an ItemsControl (myItemsControl) to the list of MyCustomControls that exist in MyUserControl at run-time. Therefore, I have exposed the List from MyUserControl through a dependency property.
I am experiencing unexpected behavior from this strategy. I would like the ItemsControl to take the List and use each control instance inside as an object with data values that can fill in the ItemsControl's DataTemplate. However, it is not doing that. Instead, it is basically ignoring the DataTemplate altogether, and simply re-rendering all the controls that are in the list/ItemsSource.
In summary, if I use a list of controls as an ItemsSource for an ItemsControl, it does not use them as data objects but instead renders them as control instances.
Surprisingly, if I attempt to do the same thing but use a ListBox instead of an ItemsControl, the databinding works as expected. I do not want to use a ListBox for other reasons. Does anyone know what the difference is between a ListBox and an ItemsControl that affects this behavior?
Edit: I've found another user who's had the same issue with no listed resolution here: msdn social forum post
After using Reflector to examine the ItemsControl code, the IsItemItsOwnContainerOverride method returns true if the item is a UIElement. You can create a subclass of ItemsControl, and change this method to:
protected override bool IsItemItsOwnContainerOverride(object item)
{
return (item is ContentPresenter);
}
If you then use that class instead of the ItemsControl, it will work as expected, but won't have the undesired functionality of ListBox.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With