Using the <UIElement> list as the Items source for the ItemsControl element causes the DataTemplate not to be applied

I created a custom panel (MyCustomControl) that can contain other controls and can be customized using dependency properties. Inside another user control (MyUserControl), I have several instances of MyCustomControl configured in XAML.

Outside of the user control, I am trying to bind the ItemsControl (myItemsControl) to the list of MyCustomControls that exist in MyUserControl at runtime. Therefore, I expanded the list from MyUserControl through the dependency property.

I experience unexpected behavior in this strategy. I would like the ItemsControl to take the List and use each instance of the control internally as an object with data values ​​that the ItemControl DataTemplate can populate. However, it is not. Instead, it basically ignores the DataTemplate as a whole and simply redraws all the controls that are in the / ItemsSource list.

In general, if I use the list of controls as ItemsSource for ItemsControl, it does not use them as data objects, but instead displays them as control instances.

Surprisingly, if I try to do the same, but use a ListBox instead of an ItemControl, the data binding works as expected. I do not want to use ListBox for other reasons. Does anyone know what is the difference between ListBox and ItemsControl, which affects this behavior?

Edit: I found another user who had the same problem without the resolution specified here: msdn social forum post

+4
source share
1 answer

After using the Reflector to test the ItemsControl code, the IsItemItsOwnContainerOverride method returns true if the item is a UIElement. You can subclass ItemsControl and change this method to:

protected override bool IsItemItsOwnContainerOverride(object item) { return (item is ContentPresenter); } 

If you then use this class instead of ItemsControl, it will work as expected, but will not have unwanted ListBox functions.

+5
source

All Articles