Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortcut to a control in WPF

Tags:

wpf

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?

like image 389
patrick Avatar asked Dec 16 '22 14:12

patrick


2 Answers

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

like image 72
17 of 26 Avatar answered Jan 08 '23 02:01

17 of 26


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>
like image 41
H.B. Avatar answered Jan 08 '23 01:01

H.B.