代码之家  ›  专栏  ›  技术社区  ›  Jeroen

TabControl/TabPanel/TabItem的WPF样式

  •  7
  • Jeroen  · 技术社区  · 14 年前

    WPF: Center TabItems in a TabControl

    <TabControl>
        <TabControl.Resources>
            <Style TargetType="{x:Type TabPanel}">
                <Setter Property="HorizontalAlignment" Value="Center" />
            </Style>
        </TabControl.Resources>
    
        <TabItem Header="Test 1" />
        <TabItem Header="Test 2" />
        <TabItem Header="Test 3" />
        <TabItem Header="Test 4" />
    </TabControl>
    

    虽然这很好,但我很想把资源和样式移到更好的位置(样式表之类的)。我的第一次尝试是移动 <TabControl.Resources> 标记到 <Window.Resources> 但这不起作用。我试过几种不同的方法,但都没有成功。下面是一个我有点期待的尝试的例子:

    <!-- Doesn't work as expected: -->
    <Window.Resources>
        <Style TargetType="{x:Type TabPanel}">
            <Setter Property="HorizontalAlignment" Value="Center" />
        </Style>
    </Window.Resources>
    

    搜索网络和msdn并没有帮我解决问题,反而给我留下了第二个(相关的)问题:到底是什么 TabPanel,它与TabControl有什么关系?

    任何帮助和提示将不胜感激。

    (已编辑:在上一个示例中注释代码不适合我。)

    2 回复  |  直到 7 年前
        1
  •  13
  •   NVM    14 年前

    alt text

        2
  •  2
  •   Crispy    14 年前

    http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.tabpanel.aspx

    <Style  TargetType="{x:Type TabControl}">
            <Setter Property="OverridesDefaultStyle" Value="True" />
            <Setter Property="SnapsToDevicePixels" Value="True" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type TabControl}">
                        <Grid KeyboardNavigation.TabNavigation="Local">
                            <Grid.RowDefinitions>
                                <RowDefinition Height="Auto"/>
                                <RowDefinition Height="*"/>
                            </Grid.RowDefinitions>
                            <TabPanel Name="HeaderPanel"
                                      Grid.Row="0"
                                      Panel.ZIndex="1" 
                                      Margin="0,0,4,-1" 
                                      IsItemsHost="True"
                                      KeyboardNavigation.TabIndex="1"
                                      HorizontalAlignment="Center"/>
                          </Grid>
    
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>