I have a TabControl with multiple TabItems. In each TabItem there needs to be this particular UserControl. Right now I'm creating X instances of the control where X is the number of TabItems I have. So this seems like a bad way to do it. So I'm wondering is there a way to have 1 instance of a control, but multiple locations for it. I know that each control can only have one parent so it seems like the answer is no.
[TabItem1]
[CommandLine Control]
[Content unique to TabItem1]
[TabItem2]
[CommandLine Control]
[Content unique to TabItem2]
Is it possible to have one instance of [CommandLine Control]
but in these two locations?
If you use a data template for your control and databind the tab control to a collection then the framework will only create one instance of the control and swap out its data context as you change tab items.
You can find a more detailed discussion here: Why do tab controls reuse View instances when changing tab
You can achieve this using triggers which ensure that the control is not in two places at the same time, e.g.
<TabControl>
<TabControl.Resources>
<!-- Define control which is to be reused in resources -->
<TextBox x:Key="SharedTB" Text="test"/>
<!-- This style gets the shared control only if the parent
TabItem is selected -->
<Style x:Key="LoadTBStyle" TargetType="{x:Type ContentControl}">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=TabItem}, Path=IsSelected}"
Value="True">
<Setter Property="Content" Value="{StaticResource SharedTB}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TabControl.Resources>
<TabItem Header="TabItem 1">
<StackPanel>
<TextBlock Text="Lorem Ipsum"/>
<ContentControl Style="{StaticResource LoadTBStyle}"/>
</StackPanel>
</TabItem>
<TabItem Header="TabItem 2">
<StackPanel>
<TextBlock Text="Dolor Sit"/>
<ContentControl Style="{StaticResource LoadTBStyle}"/>
</StackPanel>
</TabItem>
</TabControl>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With