Background:
In WPF, we have ItemsControls which expose an ItemsSource dependency property. The behavioral contract which is established for the items control is that given a collection of objects and setting ItemsControl.ItemsSource to that collection, for each object derived from UIElement, the element will be rendered and for all other types, a TextBlock is generated and the Text property is set to the results of "ToString()" called on that instance, unless a DataTemplate is set and the template data type matches the instance type, in which case the template is applied to the instance and the resulting visual tree is used for the item display. This is important because ContextualTabGroup is an ItemsControl, but problems arise when attempting to use it like this.
Issue:
When a ContextualTabGroup is created, and the ItemsSource is bound to a collection of (view-model) objects, and an ItemTemplate is set, an error is generated by the OnValidateItems method in the ContextualTabGroup: System.ArgumentException - "Only Tab controls may be added as items of a ContextualTabGroup." This issue is observed in the following code:
public class MvvmTabGroup : ContextualTabGroup
{
public MvvmTabGroup()
{
var labelBinding = new Binding { Path = new PropertyPath("Label") };
SetBinding(LabelProperty, labelBinding);
var factory = new FrameworkElementFactory(typeof(Tab));
ItemTemplate = new DataTemplate(typeof(TabViewModel))
{
VisualTree = factory
};
var itemsSourceBinding = new Binding
{
Path = new PropertyPath("Tabs")
};
SetBinding(ItemsSourceProperty, itemsSourceBinding);
IsActive = true;
}
}
Note that a DataTemplate is being specified which should translate the instance found in the collection to a visual tree the root of which is a Tab. If I override ContextualTabGroup.OnValidateItems and don't call the base class, later on, the ribbon expects the object to be a Tab without ever performing a template instantiation and application: "Unable to cast object of type 'TabViewModel' to type 'ActiproSoftware.Windows.Controls.Ribbon.Controls.Tab'." This occurs in ContextualTabGroup.OnItemsChanged.
Expected result:
I want to be able to bind the ItemsSource to an arbitrary collection of objects in order to support my MVVM architecture and use ItemTemplate to generate the visuals. This would follow the behavioral expectation set with all other WPF ItemsControl controls. Is there a workaround or some modification to a subclass of ContextualTabGroup I can implement in order to achive this end?