Given the following XAML:
<TabControl DataContext="{StaticResource mainVM}" ItemsSource="{Binding MovableVM.Docked, UpdateSourceTrigger=PropertyChanged}">
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock>
<TextBlock Text="{Binding ContentTitle}"/>
</TextBlock>
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
<ContentPresenter Content="{Binding}"/>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
I expected both DataTemplates to have the same DataContext with the expected result that the actual items from the ItemsSource (a UserControl implementing the interface IMovable, see below) being displayed within separate tabs and the header of each tab to display the contents of the property ContentTitle of the same item.
The IMovable object is displayed as expected, but the binding to the ContentTitle is not working for the header. If I change the the binding in the ContentTemplate, like so…
<TabControl.ContentTemplate>
<DataTemplate>
<ContentPresenter Content="{Binding ContentTitle}"/>
</DataTemplate>
</TabControl.ContentTemplate>
…I do get the contents of the ContentTitle property instead of the item, so the property itself is bindable.
Here’s the IMovable interface:
public interface IMovable : INotifyPropertyChanged
{
string ContentTitle { get; }
}
So my question is: Is there a different DataContext in the ItemTemplate (if so, what is it?) or is there another reason the binding in the ItemTemplate isn’t working as I expect?
Update:
I’ve created a small example application that shows the problem clearly. If things had worked as expected, there would be a text below each Ellipse in each tab, and the DataContext of the Ellipse would not be null. It can be downloaded here: Example App
Update
It works if using a custom class Foo::DependencyObject and making the ContentTitle property into a DependencyProperty. Though changing the property in the original class does not work. I need to sleep on this….
Update
I’ve narrowed down the problem, but the findings are not at all what I expected. WpfApplication2 shows that adding items to the ItemsSource that are either POCO or derived from DependedcyObject works as expected. However, items derived from UserControl do not give the expected result. I would appreciate if someone you have a look at it. Simply run the application and you’ll see that one Tab header is missing the text.
The problem here is that the DataTemplate will see an object witch inherits from Visual. This type of object do not need any visual representation through a DataTemplate. There is a discussion about it on this post.
DataTemplate DataType property doesn’t work on types inherited from Control