The existing question had an answer, but it seems to recreate the control when the tab index changes. Can I prevent this and keep the controls?
<TabControl Name="MyTabControl" IsSynchronizedWithCurrentItem="True" >
<TabControl.Resources>
<DataTemplate x:Shared="False" x:Key="MyTemplate">
<TextBox></TextBox>
</DataTemplate>
<Style TargetType="{x:Type TabItem}">
<Setter Property="ContentTemplate" Value="{StaticResource MyTemplate}"/>
</Style>
</TabControl.Resources>
</TabControl>
code behind
public partial class MainWindow : Window
{
ObservableCollection<string> Tabs = new ObservableCollection<string>();
public MainWindow()
{
InitializeComponent();
Tabs = new ObservableCollection<string>();
Tabs.Add("Tab1");
Tabs.Add("Tab2");
MyTabControl.ItemsSource = Tabs;
}
}
A workaround... seems to work for now.
<TabControl Name="MyTabControl">
<TabControl.Resources>
<DataTemplate x:Key="MyTemplate">
<ContentControl Content="{Binding RealControl}"></ContentControl>
</DataTemplate>
<Style TargetType="{x:Type TabItem}">
<Setter Property="ContentTemplate" Value="{StaticResource MyTemplate}"/>
<Setter Property="Header" Value="{Binding Header}"/>
</Style>
</TabControl.Resources>
</TabControl>
code behind
public partial class MainWindow : Window
{
ObservableCollection<Thing> Tabs = new ObservableCollection<Thing>();
public MainWindow()
{
InitializeComponent();
Tabs = new ObservableCollection<Thing>();
Tabs.Add(new Thing("Tab1"));
Tabs.Add(new Thing("Tab2"));
MyTabControl.ItemsSource = Tabs;
}
}
class Thing
{
public Thing(string name)
{
Header = name;
}
public string Header { get; set; }
public TextBox RealControl { get; set; } = new TextBox();
}