So i have this custom Progress-bar that i put inside ListView column:
<Style x:Key="CustomProgressBar" TargetType="ProgressBar" >
<Setter Property="Template" >
<Setter.Value>
<ControlTemplate TargetType="ProgressBar">
<Border BorderBrush="Gray" BorderThickness="1" Background="Gray" CornerRadius="0" Padding="0" >
<Grid x:Name="PART_Track">
<Rectangle x:Name="PART_Indicator" HorizontalAlignment="Left" Fill="MediumSeaGreen" />
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
ListView
<ListView.Resources>
<DataTemplate x:Key="MyDataTemplate">
<Grid Margin="-6" Height="22">
<ProgressBar
Name="progressBarColumn"
Maximum="100"
Value="{Binding Progress, UpdateSourceTrigger=PropertyChanged}"
Width="{Binding Path=Width, ElementName=ProgressCell}"
Margin="0"
Style="{StaticResource CustomProgressBar}" />
<TextBlock
Text="{Binding Path=Value, ElementName=progressBarColumn, StringFormat={}{0:N1}%}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
FontSize="11.5"
Foreground="Gainsboro"
Margin="0,1,0,0"/>
</Grid>
</DataTemplate>
</ListView.Resources>
So as you can see my Progress-bar color is Gray and while start to fill the color become MediumSeaGreen.
So i want the color will be Gray and while start to fill i want this color become Yellow and only when its value reach 100% i want it to be MediumSeaGreen.
Is it possible ?
All you need is an implementation for the IValueConverter interface such as:
public class ProgressToColorConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
var progress = (double)value;
//your coloring conditions here, just return the color based on the progress value
if (progress == 100d)
{
return Brushes.MediumSeaGreen;
}
if (progress >= 0.01d)
{
return Brushes.Yellow;
}
return Brushes.Gray;
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
then add it to your your resources:
<Window.Resources>
<local:ProgressToColorConverter x:Key="ProgressToColorConverter"/>
</Window.Resources>
and use it in your progress bar as
<ProgressBar ...
Foreground="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Value, Converter={StaticResource ProgressToColorConverter}}"/>
it is possible. use a Style on rectanle with default setter for Yellow color and change it to MediumSeaGreen via trigger when ProgressBar.Value reaches 100
<Rectangle x:Name="PART_Indicator" HorizontalAlignment="Left">
<Rectangle.Style>
<Style TargetType="Rectangle">
<Setter Property="Fill" Value="Yellow"/>
<Style.Triggers>
<DataTrigger Value="100" Binding="{Binding Path=Value, RelativeSource={RelativeSource AncestorType=ProgressBar}}">
<Setter Property="Fill" Value="MediumSeaGreen"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Rectangle.Style>
</Rectangle>
Solution: Please look at Ilan answer!
I am currently working on some CustomControls and this is one of them. Depending on the DirectionProperty i want to change the direction of the linearGradientBrush with the DataTrigger. I am not really able to get it working and hope for your help.
It looks like the DataTrigger isn't really able to get the Value or the Direction. Thanks in advance
SanHolo
EDIT: Doing it like that i get an error:
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='CustomControlLibrary.ColoredProgress', AncestorLevel='1''. BindingExpression:Path=Direction; DataItem=null; target element is 'ColoredProgress' (Name=''); target property is 'NoTarget' (type 'Object')
C#
using System.Windows;
using System.Windows.Controls;
namespace CustomControlLibrary
{
public class ColoredProgress : Control
{
public enum colorDirection { Increase, Decrease }
private static DependencyProperty ProgressProperty =
DependencyProperty.Register("Progress", typeof(double), typeof(ColoredProgress), new PropertyMetadata(0.00));
private static DependencyProperty DirectionProperty =
DependencyProperty.Register("Direction", typeof(colorDirection), typeof(ColoredProgress), new PropertyMetadata(colorDirection.Increase));
public double Progress
{
get { return (double)GetValue(ProgressProperty); }
set { SetValue(ProgressProperty, converter(value)); }
}
public colorDirection Direction
{
get { return (colorDirection)GetValue(DirectionProperty); }
set { SetValue(DirectionProperty, value); }
}
public ColoredProgress()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(ColoredProgress), new FrameworkPropertyMetadata(typeof(ColoredProgress)));
this.Loaded += ColoredProgress_Loaded;
}
private void ColoredProgress_Loaded(object sender, RoutedEventArgs e)
{
double height = (double)GetValue(ColoredProgress.ActualHeightProperty);
SetValue(ProgressProperty, height - (height * Progress));
}
//takes a double between 0-1 (percent of the ProgressBar) and converts it to the value needed in the design
private double converter(double percentage)
{
double height = (double)GetValue(ColoredProgress.ActualHeightProperty);
return height - (height * percentage);
}
}
}
XAML
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:CustomControlLibrary">
<Style TargetType="{x:Type local:ColoredProgress}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:ColoredProgress}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
RenderTransformOrigin="0.5, 0.5"
DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:ColoredProgress}}}">
<Grid x:Name="PART_Bar">
<Grid Background="Transparent" Panel.ZIndex="1">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Rectangle Fill="{TemplateBinding Background}" Height="{Binding Path=Progress, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
<Grid Panel.ZIndex="0">
<Grid.RowDefinitions>
<RowDefinition Height="*" x:Name="increase"/>
<RowDefinition Height="0" x:Name="decrease"/>
</Grid.RowDefinitions>
<Rectangle Grid.Row="0">
<Rectangle.Fill>
<LinearGradientBrush StartPoint="0.5,1" EndPoint="0.5,0">
<GradientStop Color="Yellow" Offset="0.0" />
<GradientStop Color="Red" Offset="1.0" />
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
<Rectangle Grid.Row="1">
<Rectangle.Fill>
<LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
<GradientStop Color="Yellow" Offset="0.0" />
<GradientStop Color="Red" Offset="1.0" />
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
</Grid>
</Grid>
</Border>
<ControlTemplate.Triggers>
<DataTrigger Binding="{Binding Path=Direction, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:ColoredProgress}}}" Value="colorDirection.Decrease">
<Setter TargetName="increase" Property="Height" Value="0"/>
<Setter TargetName="decrease" Property="Height" Value="*"/>
</DataTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
please use the regular triggers:
<ControlTemplate TargetType="{x:Type local:ColoredProgress}">
...
<ControlTemplate.Triggers>
<Trigger Property="Direction" Value="Decrease">
<Setter TargetName="increase" Property="Height" Value="0"/>
<Setter TargetName="decrease" Property="Height" Value="*"/>
</Trigger>
<Trigger Property="Direction" Value="Increase">
<Setter TargetName="increase" Property="Height" Value="*"/>
<Setter TargetName="decrease" Property="Height" Value="0"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
As I understand the data trigger go to the DataContext to check for the value, since you've defined a Direction as a dependency property of your control you, can get the value directly. More over you can't point the data context because you haven't any property in you data context that can provide you with the value you need. That is why you get the binding expression error.
Let me know if you need more explanation.
Regards.
I haven't run your code, but I suppose your problem is that your value binding in the DataTrigger is not set correctly to the Enum value you expect.
Try this: (Note the new Value binding)
<ControlTemplate.Triggers>
<DataTrigger Binding="{Binding Path=Direction, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:ColoredProgress}}}"
Value="{x:Static local:colorDirection.Decrease}">
<Setter TargetName="increase" Property="Height" Value="0"/>
<Setter TargetName="decrease" Property="Height" Value="*"/>
</DataTrigger>
</ControlTemplate.Triggers>
I suppose it should work, but I didn't check the rest of the code, so feel free to update your progress in here.
I am trying to make a custom tooltip control that is used for TextBoxes.
It will look like this:
...except for some pixels that comes from the background components that I have gimped away as good as possible.
The idea comes from:
How to implement Balloon message in a WPF application
The problem is that the code behind of my custom control never gets the validation object (that should be passed to it via the trigger in generic.xaml).
Why not?
generic.xaml:
<Style TargetType="{x:Type TextBox}" x:Name="tb">
<Setter Property="Width" Value="200" />
<Setter Property="Background" Value="{StaticResource InputBackgroundColor}" />
<Setter Property="BorderBrush" Value="{StaticResource InputBorderBrush}" />
<Setter Property="HorizontalAlignment" Value="Left" />
<Setter Property="Margin" Value="5,0,0,5" />
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip">
<Setter.Value>
<Windows:ValidationBalloonPopupWindow
Validation="{Binding Path=Validation, ElementName=tb}" />
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
As you see, I try to refer to Validation by using ElementName of tb.
Seems like Name is not used in templates. If I change to x:Key instead, all my textboxes becomes like 10 pixels wide. Probably not the right thing to do in other words.
The code behind, ValidationBalloonPopupWindow.xaml.cs:
using System.Windows;
using System.Windows.Controls;
namespace Foo.ToolTips
{
public partial class ValidationBalloonPopupWindow : ToolTip
{
public ValidationBalloonPopupWindow()
{
InitializeComponent();
}
public static DependencyProperty ValidationProperty
= DependencyProperty.Register("Validation", typeof(object), typeof(ValidationBalloonPopupWindow),
new PropertyMetadata(null, OnChangedValidationByBinding));
private static void OnChangedValidationByBinding
(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((ValidationBalloonPopupWindow)d).OnChangedValidationByBinding(e.NewValue);
}
public void OnChangedValidationByBinding(object newValue)
{
txtMessage.Text = newValue.GetType().Name;
}
private object _validation;
public object Validation
{
get
{
return _validation;
}
set
{
_validation = value;
txtMessage.Text = _validation.GetType().Name;
}
}
}
}
Which has a setter that should run, I have tried to put a lot of breakpoints in this file without success.
The xaml for the control itself, ValidationBalloonPopupWindow.xaml:
<ToolTip x:Class="FRAM.Windows.ValidationBalloonPopupWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Background="Transparent" BorderBrush="Transparent" HasDropShadow="false"
Placement="Bottom"
Height="Auto" Width="Auto">
<Grid Height="126" Width="453">
<Border Margin="7,13,0,0"
CornerRadius="10,10,10,10" Grid.ColumnSpan="4" HorizontalAlignment="Left" Width="429" Height="82" VerticalAlignment="Top" Grid.RowSpan="2">
<Border.Effect>
<DropShadowEffect Color="#FF474747" />
</Border.Effect>
<Border.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF58C2FF" Offset="0" />
<GradientStop Color="#FFFFFFFF" Offset="1" />
</LinearGradientBrush>
</Border.Background>
<StackPanel Orientation="Vertical">
<Label Content="Title" Height="31" HorizontalAlignment="Left"
Margin="12,8,0,0" Name="lblCaption" FontSize="16" FontWeight="Bold" />
<TextBlock Margin="18,0,0,0" Name="txtMessage" Width="378" HorizontalAlignment="Left">Body</TextBlock>
</StackPanel>
</Border>
<Path Data="M25,25L10.9919,0.64 0.7,25" Fill="#FF58C2FF" HorizontalAlignment="Left"
Margin="32,3,0,0" Stretch="Fill" Width="22" Height="10" VerticalAlignment="Top" />
</Grid>
</ToolTip>
Instead of referring by name, get the Textbox itself by using RelativeSource binding.
Try something like this:
<Setter Property="ToolTip">
<Setter.Value>
<Windows:ValidationBalloonPopupWindow
Validation="{Binding RelativeSource={RelativeSource Self}, Path=Validation}" />
</Setter.Value>
</Setter>
I try to create a ControlTemplate for my Label like this :
<Style TargetType="{x:Type Label}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Label}">
<Grid x:Name="LayoutRoot" Background="White">
<Rectangle Height="30" HorizontalAlignment="Left" Margin="10"
Stroke="transparent"
VerticalAlignment="Top" Width="3"
Fill="#FF259FED" />
<ContentPresenter HorizontalAlignment="Left" Margin="17,0,0,0" RecognizesAccessKey="True"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="Foreground" Value="#7A7E81" />
<Setter Property="FontWeight" Value="Bold" />
</Style>
I want to fill color of rectangle when i create my control, like this for example :
<Label Content="Prénom" VerticalAlignment="Top" CouleurRectangle="#FF259FED" />
So, how can I change Property "Fill" in my controlTemplate to set dynamicly color of rectangle when i create control ?
thank's a lot.
Edit : this is the solution , i create a new class who inherit from Label like this :
Public Class LblTitreChamp
Inherits Label
Public Shared ReadOnly CouleurProperty As DependencyProperty =
DependencyProperty.Register("CouleurRectangle", GetType(SolidColorBrush), GetType(LblTitreChamp))
''' <summary>Propriété pour insérer une couleur au début du Label</summary>
Public Property CouleurRectangle As SolidColorBrush
Get
Return GetValue(CouleurProperty)
End Get
Set(ByVal value As SolidColorBrush)
SetValue(CouleurProperty, value)
End Set
End Property
End Class
then, in my COntrolTemplate :
<Style TargetType="{x:Type local:LblTitreChamp}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:LblTitreChamp}">
<Grid x:Name="LayoutRoot" Background="White">
<Rectangle Height="30" HorizontalAlignment="Left" Margin="10"
Stroke="transparent"
VerticalAlignment="Top" Width="3"
Fill="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Label}}, Path=CouleurRectangle}"/>
<ContentPresenter HorizontalAlignment="Left" Margin="17,0,0,0" RecognizesAccessKey="True"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="Foreground" Value="#7A7E81" />
<Setter Property="FontWeight" Value="Bold" />
</Style>
and finally, to creat a new label :
<my:LblTitreChamp Content="ID" VerticalAlignment="Top" CouleurRectangle="Black" />
thank's a lot for you :)
hi set Fill={TemplateBinding CouleurRectangle} .Hope this will help. And i Expect that you have created a custom Label class That inherit from Label and has DependencyProperty CouleurRectangle.
Since your label is not a CustomControl, then you cannot dynamically make a property on that so the best possible way is to use the background property of label
...
<Rectangle Height="30" ...
Fill="{TemplateBinding Background}" />
...
Else create a CustomControl inheriting the Label and make a new dependency property and also define a XAML template style for it.
How to create trapezoid tabs in WPF tab control? I'd like to create non rectangular tabs that look like tabs in Google Chrome or like tabs in code editor of VS 2008.
Can it be done with WPF styles or it must be drawn in code?
Is there any example of code available on internet?
Edit:
There is lots of examples that show how to round corners or change colors of tabs, but I could not find any that changes geometry of tab like this two examples:
VS 2008 Code Editor Tabs
Google Chrome tabs
Tabs in this two examples are not rectangles, but trapezes.
I tried to find some control templates or solutions for this problem on internet, but I didn’t find any “acceptable” solution for me. So I wrote it in my way and here is an example of my first (and last=)) attempt to do it:
<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
}
}
These two converters I wrote to adjust tab size to its content. Actually, I making Path object depending on content size. If you don’t need tabs with various widths, you can use some modified copy of this:
<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>
screen:
sample project(vs2010)
Note: This is only an appendix to rooks' great answer.
While rooks' solution was working perfectly at runtime for me I had some trouble when opening the MainWindow in the VS2010 WPF designer surface: The designer threw exceptions and didn't display the window. Also the whole ControlTemplate for TabItem in TabControl.xaml had a blue squiggle line and a tooltip was telling me that a NullReferenceException occurred. I had the same behaviour when moving the relevant code into my application. The problems were on two different machines so I believe it wasn't related to any problems of my installation.
In case that someone experiences the same issues I've found a fix so that the example works now at runtime and in the designer as well:
First: Replace in the TabControl-XAML code ...
<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>
... by ...
<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>
Second: Replace at the end of the Convert method of the ContentToPathConverter class ...
return ps;
... by ...
PathFigure figure = new PathFigure(new Point(1, 0), ps, false);
PathGeometry geometry = new PathGeometry();
geometry.Figures.Add(figure);
return geometry;
I have no explanation why this runs stable in the designer but not rooks' original code.
I just finished a Google Chrome-like Tab Control for WPF. You can find the project at https://github.com/realistschuckle/wpfchrometabs and blog posts describing it at
Google Chrome-Like WPF Tab Control
ChromeTabControl and Visual Children in WPF
WPF Chrome Tabs Functioning
Hope that helps you get a better understanding of building a custom tab control from scratch.
<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>
I know this is old but I'd like to propose:
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>
ViewModel:
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;
}
}
}
Main:
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());
}
}
}
}
yep, you can do that--basically all you have to do is make a custom control-template. Check out http://www.switchonthecode.com/tutorials/the-wpf-tab-control-inside-and-out
(Dead link. WaybackMachine redirects here)
for a tutorial. Just googling "wpf" "tabcontrol" "shape" turns up pages of results.
I have not tried this myself, but you should be able to replace the tag(s) in the template with tags to get the shape that you want.
To slope both left and right tab edges, here is a modification of Slauma's enhancement to rook's accepted answer. This is a replacement of Convert method of the ContentToPathConverter class:
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;
}
Also in TabControl's ControlTemplate, add left (and optionally right) margins to the container of the tab items (the only change is added 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"/>
Issue: There is a slight visual "glitch" at bottom of left edge of tab, when it is not the selected tab. I think it is related to "going backwards" to start before beginning of tab area. Or else related to drawing of line line at bottom of tab (which doesn't know we start before the left edge of the tabs "normal" rectangle).