I am doing a WPF application with a TabControl. At the beginning I had a TabControl bound to ObservableCollection of TabBase items, where TabBase is a base class for tab viewmodel:
<TabControl
IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding Tabs}"
ItemTemplate="{StaticResource ClosableTabTemplate}"
...
public ObservableCollection<TabBase> Tabs { get; private set; }
...
public abstract class TabBase : ViewModelBase
...
public abstract class ViewModelBase : INotifyPropertyChanged
{
public virtual string DisplayName { get; protected set; }
...
<DataTemplate x:Key="ClosableTabTemplate">
<DockPanel Width="120">
<Button
Command="{Binding Path=CmdClose}"
Content="X"
/>
<ContentPresenter
Content="{Binding Path=DisplayName}">
</ContentPresenter>
</DockPanel>
</DataTemplate>
But I've faced with an issue when I switch tabs it looks like current tab is being created each time, even if it was already opened before. Searching thru StackOverflow I've found the solution here with reference to here. I've replaced using of declarative ItemsSource with dynamic creation of tabs from code. Tabs switching performance issue was resolved, but tab headers have lost link to template, so instead of tab header with caption and close button I see just a little tab header without anything. Playing a bit with tab creation code, I was able to restore tab size and close button, but without binding - there is no caption and close button doesn't work (5 lines with item.Header restored original tab size):
private void AddTabItem(TabBase view)
{
TabItem item = new TabItem();
item.DataContext = view;
item.Content = new ContentControl();
(item.Content as ContentControl).Focusable = false;
(item.Content as ContentControl).SetBinding(ContentControl.ContentProperty, new Binding());
item.Header = new ContentControl();
(item.Header as ContentControl).DataContext = view;
(item.Header as ContentControl).Focusable = false;
(item.Header as ContentControl).SetBinding(ContentControl.ContentProperty, new Binding());
item.HeaderTemplate = (DataTemplate)FindResource("ClosableTabTemplate");
tabControl.Items.Add(item);
}
The question is, how can I make ItemTemplate working for TabControl without ItemsSource binding?