TabControl's TabItems sharing same content… Do Not Want

后端 未结 3 583
走了就别回头了
走了就别回头了 2021-01-04 12:07

The following example xaml causes each tab item to share the same TextBox. It makes sense, on some level I guess... but it\'s unexpected behavior, and almost feels like a bu

相关标签:
3条回答
  • 2021-01-04 12:49

    It will work if you define a usercontrol that has the tab content in it. I created the following usercontrol:

    <UserControl x:Class="SO_Testing.TextBoxUC"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
                 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
                 mc:Ignorable="d" 
                 d:DesignHeight="300" d:DesignWidth="300">
        <Grid>
            <TextBox/>
        </Grid>
    </UserControl>
    

    Then I modified my window xaml to be this:

    <Window x:Class="SO_Testing.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:local="clr-namespace:SO_Testing"
            Title="MainWindow" Height="350" Width="525">
        <Grid>
            <TabControl>
                <TabItem Name="tab1" Header="Test">
                    <local:TextBoxUC/>
                </TabItem>
                <TabItem Name="tab2" Header="Test 2">
                    <local:TextBoxUC/>
                </TabItem>
            </TabControl>
        </Grid>
    </Window>
    

    This may not be exactly what you are wanting, but at least the layout of each tab is only defined in one place and you can then assign a datacontext to each usercontrol to show the values for each of your tabs.

    0 讨论(0)
  • 2021-01-04 12:52

    I suspect there's a nicer way to achieve whatever it is you're trying to achieve, but I think this will work (would test but I'm on linux atm):

    <TabControl>
        <TabControl.Resources>
            <Style TargetType="TabItem" x:Shared="False">
                <Setter Property="ContentTemplate">
                    <Setter.Value>
                        <DataTemplate>
                            <TextBox />
                        </DataTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </TabControl.Resources>
        <TabItem Name="tab1" />
        <TabItem Name="tab2" />
    </TabControl>
    
    0 讨论(0)
  • 2021-01-04 12:53

    I had the same problem, and found this post explaining why this happens and how to workaround it. This is the link, just in case someone else come around with the same issue:

    http://www.codeproject.com/Articles/460989/WPF-TabControl-Turning-Off-Tab-Virtualization

    0 讨论(0)
提交回复
热议问题