views:

441

answers:

2

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

+1  A: 

See the answer to this question

Arcturus
+4  A: 

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.

Abe Heidebrecht
Thank you very much, this worked! I did have to change the method definition slightly... protected override bool IsItemItsOwnContainerOverride(object item)
YeahStu