如何在WPF选项卡控件中创建梯形标签页

82
如何在WPF标签控件中创建梯形选项卡?我想创建非矩形的选项卡,看起来像Google Chrome的选项卡或VS 2008代码编辑器中的选项卡。
这可以使用WPF样式完成还是必须在代码中绘制?
互联网上有没有可用的代码示例?
注:有很多示例显示如何圆角或更改选项卡的颜色,但我找不到任何改变选项卡几何图形的示例,就像这两个示例一样: VS 2008代码编辑器选项卡
Google Chrome选项卡
这两个示例中的选项卡不是矩形而是梯形。
7个回答

106

我曾试图在互联网上寻找一些控件模板或解决方案来解决这个问题,但是我没有找到任何对我来说“可接受”的解决方案。所以我按照自己的方式编写了它,并且这里是我第一次(也是最后一次=)尝试做到这一点的示例:

<Window x:Class="TabControlTemplate.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:src="clr-namespace:TabControlTemplate"
    Title="Window1" Width="600" Height="400">
<Window.Background>
    <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
        <GradientStop Color="#FF3164a5" Offset="1"/>
        <GradientStop Color="#FF8AAED4" Offset="0"/>
    </LinearGradientBrush>
</Window.Background>
<Window.Resources>
    <src:ContentToPathConverter x:Key="content2PathConverter"/>
    <src:ContentToMarginConverter x:Key="content2MarginConverter"/>

    <SolidColorBrush x:Key="BorderBrush" Color="#FFFFFFFF"/>
    <SolidColorBrush x:Key="HoverBrush" Color="#FFFF4500"/>
    <LinearGradientBrush x:Key="TabControlBackgroundBrush" EndPoint="0.5,0" StartPoint="0.5,1">
        <GradientStop Color="#FFa9cde7" Offset="0"/>
        <GradientStop Color="#FFe7f4fc" Offset="0.3"/>
        <GradientStop Color="#FFf2fafd" Offset="0.85"/>
        <GradientStop Color="#FFe4f6fa" Offset="1"/>
    </LinearGradientBrush>
    <LinearGradientBrush x:Key="TabItemPathBrush" StartPoint="0,0" EndPoint="0,1">
        <GradientStop Color="#FF3164a5" Offset="0"/>
        <GradientStop Color="#FFe4f6fa" Offset="1"/>
    </LinearGradientBrush>

    <!-- TabControl style -->
    <Style x:Key="TabControlStyle" TargetType="{x:Type TabControl}">
        <Setter Property="BorderThickness" Value="1"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="TabControl">
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto"/>
                            <RowDefinition Height="*"/>
                        </Grid.RowDefinitions>
                        <Border Grid.Row="1" BorderThickness="2,0,2,2" Panel.ZIndex="2" CornerRadius="0,0,2,2"
                                BorderBrush="{StaticResource BorderBrush}"
                                Background="{StaticResource TabControlBackgroundBrush}">
                            <ContentPresenter ContentSource="SelectedContent"/>
                        </Border>
                        <StackPanel Orientation="Horizontal" Grid.Row="0" Panel.ZIndex="1" IsItemsHost="true"/>
                        <Rectangle Grid.Row="0" Height="2" VerticalAlignment="Bottom"
                                   Fill="{StaticResource BorderBrush}"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <!-- TabItem style -->
    <Style x:Key="{x:Type TabItem}" TargetType="{x:Type TabItem}">
        <Setter Property="SnapsToDevicePixels" Value="True"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="TabItem">
                    <Grid x:Name="grd">
                        <Path x:Name="TabPath" StrokeThickness="2"
                              Margin="{Binding ElementName=TabItemContent, Converter={StaticResource content2MarginConverter}}"
                              Stroke="{StaticResource BorderBrush}"
                              Fill="{StaticResource TabItemPathBrush}">
                            <Path.Data>
                                <PathGeometry>
                                    <PathFigure IsClosed="False" StartPoint="1,0" 
                                                Segments="{Binding ElementName=TabItemContent, Converter={StaticResource content2PathConverter}}">
                                    </PathFigure>
                                </PathGeometry>
                            </Path.Data>
                            <Path.LayoutTransform>
                                <ScaleTransform ScaleY="-1"/>
                            </Path.LayoutTransform>
                        </Path>
                        <Rectangle x:Name="TabItemTopBorder" Height="2" Visibility="Visible"
                                   VerticalAlignment="Bottom" Fill="{StaticResource BorderBrush}"
                                   Margin="{Binding ElementName=TabItemContent, Converter={StaticResource content2MarginConverter}}" />
                        <ContentPresenter x:Name="TabItemContent" ContentSource="Header"
                                          Margin="10,2,10,2" VerticalAlignment="Center"
                                          TextElement.Foreground="#FF000000"/>
                    </Grid>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True" SourceName="grd">
                            <Setter Property="Stroke" Value="{StaticResource HoverBrush}" TargetName="TabPath"/>
                        </Trigger>
                        <Trigger Property="Selector.IsSelected" Value="True">
                            <Setter Property="Fill" TargetName="TabPath">
                                <Setter.Value>
                                    <SolidColorBrush Color="#FFe4f6fa"/>
                                </Setter.Value>
                            </Setter>
                            <Setter Property="BitmapEffect">
                                <Setter.Value>
                                    <DropShadowBitmapEffect Direction="302" Opacity="0.4" 
                                                        ShadowDepth="2" Softness="0.5"/>
                                </Setter.Value>
                            </Setter>
                            <Setter Property="Panel.ZIndex" Value="2"/>
                            <Setter Property="Visibility" Value="Hidden" TargetName="TabItemTopBorder"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>
<Grid Margin="20">
    <TabControl Grid.Row="0" Grid.Column="1" Margin="5" TabStripPlacement="Top" 
                Style="{StaticResource TabControlStyle}" FontSize="16">
        <TabItem Header="MainTab">
            <Border Margin="10">
                <TextBlock Text="The quick brown fox jumps over the lazy dog."/>
            </Border>
        </TabItem>
        <TabItem Header="VeryVeryLongTab" />
        <TabItem Header="Tab" />
    </TabControl>
</Grid>

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;

namespace TabControlTemplate
{
public partial class Window1
{
    public Window1()
    {
        InitializeComponent();
    }
}

public class ContentToMarginConverter: IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return new Thickness(0, 0, -((ContentPresenter)value).ActualHeight, 0);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}

public class ContentToPathConverter: IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var ps = new PathSegmentCollection(4);
        ContentPresenter cp = (ContentPresenter)value;
        double h = cp.ActualHeight > 10 ? 1.4 * cp.ActualHeight : 10;
        double w = cp.ActualWidth > 10 ? 1.25 * cp.ActualWidth : 10;
        ps.Add(new LineSegment(new Point(1, 0.7 * h), true));
        ps.Add(new BezierSegment(new Point(1, 0.9 * h), new Point(0.1 * h, h), new Point(0.3 * h, h), true));
        ps.Add(new LineSegment(new Point(w, h), true));
        ps.Add(new BezierSegment(new Point(w + 0.6 * h, h), new Point(w + h, 0), new Point(w + h * 1.3, 0), true));
        return ps;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}
}

我编写了这两个转换器来根据内容调整制表符大小。实际上,我根据内容大小制作Path对象。如果您不需要具有各种宽度的制表符,则可以使用此内容的某个修改副本:

我编写了这两个转换器来自动调整制表符大小,实际上是通过根据内容大小创建Path对象来实现的。如果您不需要使用不同宽度的制表符,则可以使用经过修改的此代码的副本。

<Style x:Key="tabPath" TargetType="{x:Type Path}">
      <Setter Property="Stroke" Value="Black"/>
      <Setter Property="Data">
          <Setter.Value>
              <PathGeometry Figures="M 0,0 L 0,14 C 0,18 2,20 6,20 L 60,20 C 70,20 80,0 84,0"/>
          </Setter.Value>
      </Setter>
  </Style>

屏幕:

screenshot

示例项目(vs2010)


3
@rooks:很棒的例子,谢谢!在运行时它对我有效,但是我在VS2010的WPF设计器中遇到了问题。设计器崩溃并显示NullReferenceException,似乎是由XAML中的Path.Data元素引起的。当我注释掉这个元素时,设计器就稳定了。你有什么线索可以解决这个问题吗? - Slauma
3
与此同时,我已经找到了一种解决方法,使您的示例在VS2010的设计器视图中也能正常运行:请参阅我的回答。 - Slauma
哇,这正是我刚刚花了一个多小时努力实现的。我说让设计师来设计吧!如果可以的话,我会点赞并再加100个赞。 - Ed S.
如何修改转换器以应用“正确”的贝塞尔曲线,使得左右两侧具有相同的“曲线”? - JoanComasFdz
一些与 <PathGeometry Figures=... 中使用的几何迷你语言相关的链接。路径标记语法WPF 几何迷你语言概述Blackwasp WPF 教程路径标记语法 - ToolmakerSteve
1
@JoanComasFdz - 几年后,我有了左+右边缘斜坡的答案。希望能帮助到某些人。 - ToolmakerSteve

35

注意:这只是rooks优秀回答的附录。

虽然rooks的解决方案在运行时完美运作,但当我在VS2010 WPF设计器表面打开MainWindow时遇到了一些麻烦:设计器抛出异常并且没有显示窗口。此外,在TabControl.xaml中整个TabItem的ControlTemplate都有一个蓝色的波浪线,而且工具提示告诉我发生了NullReferenceException。当我将相关代码移入我的应用程序时,我也遇到了同样的问题。这些问题出现在两台不同的计算机上,因此我认为与我的安装无关。

如果有人遇到相同的问题,我已经找到了一个修复方法,使示例现在在运行时和设计器中都能正常工作:

首先:在TabControl-XAML代码中替换...

<Path x:Name="TabPath" StrokeThickness="2"
      Margin="{Binding ElementName=TabItemContent,
               Converter={StaticResource content2MarginConverter}}"
      Stroke="{StaticResource BorderBrush}"
      Fill="{StaticResource TabItemPathBrush}">
    <Path.Data>
        <PathGeometry>
            <PathFigure IsClosed="False" StartPoint="1,0" 
                 Segments="{Binding ElementName=TabItemContent,
                            Converter={StaticResource content2PathConverter}}">
            </PathFigure>
        </PathGeometry>
    </Path.Data>
    <Path.LayoutTransform>
        <ScaleTransform ScaleY="-1"/>
    </Path.LayoutTransform>
</Path>

...由...负责...

<Path x:Name="TabPath" StrokeThickness="2"
      Margin="{Binding ElementName=TabItemContent,
               Converter={StaticResource content2MarginConverter}}"
      Stroke="{StaticResource BorderBrush}"
      Fill="{StaticResource TabItemPathBrush}"
      Data="{Binding ElementName=TabItemContent,
             Converter={StaticResource content2PathConverter}}">
    <Path.LayoutTransform>
        <ScaleTransform ScaleY="-1"/>
    </Path.LayoutTransform>
</Path>

第二步:在ContentToPathConverter类的Convert方法末尾进行替换...

return ps;

...由...提供...

PathFigure figure = new PathFigure(new Point(1, 0), ps, false);
PathGeometry geometry = new PathGeometry();
geometry.Figures.Add(figure);

return geometry;

我不知道为什么这在设计师中运行稳定,但不是在rooks的原始代码中。


根据Slauma的答案,可以看看我的回答,以使每个选项卡的左右边缘都倾斜。 - ToolmakerSteve

12

9
<Grid>
    <Grid.Resources>
        <Style TargetType="{x:Type TabControl}">
            <Setter Property="ItemContainerStyle">
                <Setter.Value>
                    <Style>
                        <Setter Property="Control.Height" Value="20"></Setter>
                        <Setter Property="Control.Template">
                            <Setter.Value>
                                <ControlTemplate TargetType="{x:Type TabItem}">
                                    <Grid Margin="0 0 -10 0">
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="10">
                                            </ColumnDefinition>
                                            <ColumnDefinition></ColumnDefinition>
                                            <ColumnDefinition Width="10"></ColumnDefinition>
                                        </Grid.ColumnDefinitions>
                                        <Path Data="M10 0 L 0 20 L 10 20 " Fill="{TemplateBinding Background}" Stroke="Black"></Path>
                                        <Rectangle Fill="{TemplateBinding Background}" Grid.Column="1"></Rectangle>
                                        <Rectangle VerticalAlignment="Top" Height="1" Fill="Black" Grid.Column="1"></Rectangle>
                                        <Rectangle VerticalAlignment="Bottom" Height="1" Fill="Black" Grid.Column="1"></Rectangle>
                                        <ContentPresenter Grid.Column="1" ContentSource="Header" />
                                       <Path Data="M0 20 L 10 20 L0 0" Fill="{TemplateBinding Background}" Grid.Column="2" Stroke="Black"></Path>
                                    </Grid>
                                    <ControlTemplate.Triggers>
                                        <Trigger Property="IsSelected" Value="True">
                                            <Trigger.Setters>
                                                <Setter Property="Background" Value="Beige"></Setter>
                                                <Setter Property="Panel.ZIndex" Value="1"></Setter>
                                            </Trigger.Setters>
                                        </Trigger>
                                        <Trigger Property="IsSelected" Value="False">
                                            <Trigger.Setters>
                                                <Setter Property="Background" Value="LightGray"></Setter>
                                            </Trigger.Setters>
                                        </Trigger>
                                    </ControlTemplate.Triggers>
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </Setter.Value>
            </Setter>
        </Style>
    </Grid.Resources>
    <TabControl>
        <TabItem Header="One" ></TabItem>
        <TabItem Header="Two" ></TabItem>
        <TabItem Header="Three" ></TabItem>
    </TabControl>
</Grid>

6

我知道这已经过时了,但我想提出以下建议:

在此输入图片描述

XAML:

    <Window.Resources>

    <ControlTemplate x:Key="trapezoidTab" TargetType="TabItem">
        <Grid>
            <Polygon Name="Polygon_Part" Points="{Binding TabPolygonPoints}" />
            <ContentPresenter Name="TabContent_Part" Margin="{TemplateBinding Margin}" Panel.ZIndex="100" ContentSource="Header" HorizontalAlignment="Center" VerticalAlignment="Center"/>
        </Grid>

        <ControlTemplate.Triggers>

            <Trigger Property="IsMouseOver" Value="False">
                <Setter TargetName="Polygon_Part" Property="Stroke" Value="LightGray"/>
                <Setter TargetName="Polygon_Part" Property="Fill" Value="DimGray" />
            </Trigger>

            <Trigger Property="IsMouseOver" Value="True">
                <Setter TargetName="Polygon_Part" Property="Fill" Value="Goldenrod" />
                <Setter TargetName="Polygon_Part" Property="Stroke" Value="LightGray"/>
            </Trigger>

            <Trigger Property="IsSelected" Value="False">
                <Setter Property="Panel.ZIndex" Value="90"/>
            </Trigger>

            <Trigger Property="IsSelected" Value="True">
                <Setter Property="Panel.ZIndex" Value="100"/>
                <Setter TargetName="Polygon_Part" Property="Stroke" Value="LightGray"/>
                <Setter TargetName="Polygon_Part" Property="Fill" Value="LightSlateGray "/>
            </Trigger>


        </ControlTemplate.Triggers>

    </ControlTemplate>

</Window.Resources>

<!-- Test the tabs-->
<TabControl Name="FruitTab">
    <TabItem Header="Apple" Template="{StaticResource trapezoidTab}" />
    <TabItem Margin="-8,0,0,0" Header="Grapefruit" Template="{StaticResource trapezoidTab}" />
    <TabItem Margin="-16,0,0,0" Header="Pear" Template="{StaticResource trapezoidTab}"/>
</TabControl>

视图模型:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Shapes;
    using System.ComponentModel;
    using System.Globalization;
    using System.Windows.Media;

    namespace TrapezoidTab
    {
        public class TabHeaderViewModel : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
            private string _tabHeaderText;
            private List<Point> _polygonPoints;
            private PointCollection _pointCollection;

            public TabHeaderViewModel(string tabHeaderText)
            {
                _tabHeaderText = tabHeaderText;
                TabPolygonPoints = GenPolygon();
            }

            public PointCollection TabPolygonPoints
            {
                get { return _pointCollection; }
                set
                {
                    _pointCollection = value;
                    if (PropertyChanged != null)
                        PropertyChanged(this, new PropertyChangedEventArgs("TabPolygonPoints"));
                }
            }

            public string TabHeaderText
            {
                get { return _tabHeaderText; }
                set
                {
                    _tabHeaderText = value;
                    TabPolygonPoints = GenPolygon();
                    if (PropertyChanged != null)
                        PropertyChanged(this, new PropertyChangedEventArgs("TabHeaderText"));
                }
            }

            private PointCollection GenPolygon()
            {
                var w = new FormattedText(_tabHeaderText, CultureInfo.GetCultureInfo("en-us"), FlowDirection.LeftToRight, new Typeface("Tahoma"), 12, Brushes.Black);
                var width = w.Width + 30;

                _polygonPoints = new List<Point>(4);
                _pointCollection = new PointCollection(4);

                _polygonPoints.Add(new Point(2, 21));
                _polygonPoints.Add(new Point(10, 2));
                _polygonPoints.Add(new Point(width, 2));
                _polygonPoints.Add(new Point(width + 8, 21));

                foreach (var point in _polygonPoints)
                    _pointCollection.Add(point);

                return _pointCollection;
            }
        }
    }

主要:

namespace TrapezoidTab
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            foreach (var obj in FruitTab.Items)
            {
                var tab = obj as TabItem;
                if (tab == null) continue;
                tab.DataContext = new TabHeaderViewModel(tab.Header.ToString());
            }
        }
    }
}

4
是的,你可以这样做——基本上你需要做的就是创建一个自定义控件模板。查看此教程:http://www.switchonthecode.com/tutorials/the-wpf-tab-control-inside-and-out链接已失效,请使用网络档案馆)以获取教程。只需在Google中搜索“wpf”、“tabcontrol”和“shape”,就会出现许多结果。
我自己没有尝试过,但你应该能够用 <Path> 标签替换模板中的 <TabItem> 标签,从而获得所需的形状。

我看了那个例子和一些其他的例子。它们都只是使用圆角并将一些颜色应用于选项卡,但它们仍然是矩形选项卡。我想要梯形的。 - zendar
你应该能够将<border>标签更改为<polygon>标签。 - Muad'Dib
是的,但即使如此,就像Chrome示例中那样,也不会有重叠。有什么想法吗? - Tom Deleu
1
我的最佳猜测是调整元素的边距设置。 - Muad'Dib

1
为了倾斜标签的左右两侧,这里修改了Slauma的增强版,以替换ContentToPathConverter类的Convert方法。rook的答案已被接受。请参考以下代码:
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var ps = new PathSegmentCollection(4);
        ContentPresenter cp = (ContentPresenter)value;
        double h = cp.ActualHeight > 10 ? 1.4 * cp.ActualHeight : 10;
        double w = cp.ActualWidth > 10 ? 1.25 * cp.ActualWidth : 10;
        // Smaller unit, so don't need fractional multipliers.
        double u = 0.1 * h;
        // HACK: Start before "normal" start of tab.
        double x0 = -4 * u;
        // end of transition
        double x9 = w + 8 * u;
        // transition width
        double tw = 8 * u;
        // top "radius" (actually, gradualness of curve. Larger value is more rounded.)
        double rt = 5 * u;
        // bottom "radius" (actually, gradualness of curve. Larger value is more rounded.)
        double rb = 3 * u;
        // "(x0, 0)" is start point - defined in PathFigure.
        // Cubic: From previous endpoint, 2 control points + new endpoint.
        ps.Add(new BezierSegment(new Point(x0 + rb, 0), new Point(x0 + tw - rt, h), new Point(x0 + tw, h), true));
        ps.Add(new LineSegment(new Point(x9 - tw, h), true));
        ps.Add(new BezierSegment(new Point(x9 - tw + rt, h), new Point(x9 - rb, 0), new Point(x9, 0), true));

        // "(x0, 0)" is start point.
        PathFigure figure = new PathFigure(new Point(x0, 0), ps, false);
        PathGeometry geometry = new PathGeometry();
        geometry.Figures.Add(figure);

        return geometry;
    }

在TabControl的控件模板中,为选项卡项的容器添加左(和可选的右)边距(唯一的更改是添加了Margin="20,0,20,0"):
<Style x:Key="TabControlStyle" TargetType="{x:Type TabControl}">
    ...
    <Setter Property="Template">
        ...
        <StackPanel Grid.Row="0" Panel.ZIndex="1" Orientation="Horizontal" IsItemsHost="true" Margin="20,0,20,0"/>

问题:当选项卡未被选中时,左边缘底部存在轻微的视觉“故障”。我认为这与在选项卡区域开始之前“倒退”有关。或者与绘制选项卡底部的线条有关(该线条不知道我们从选项卡的“正常”矩形左边缘开始)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接