Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a header to a separator in WPF?

I would like to add a header to a WPF Separator (so that it looks like the top line of a GroupBox). The purpose of this is to separate the view into different sections, and I can't use a GroupBox because the guidelines in our business say that we must use separators for that... Does someone know how to do that?

EDIT:

I know it is possible to achieve this solution by using other controls (i.e. borders and textbox), but I want to know is if an Header property can be added to the Separator object.

like image 427
Carl Avatar asked Jul 04 '11 16:07

Carl


2 Answers

You can write you own custom control

public class HeaderedSeparator : Control
{
    public static DependencyProperty HeaderProperty =
        DependencyProperty.Register(
        "Header",
        typeof(string),
        typeof(HeaderedSeparator));

    public string Header
    {
        get { return (string)GetValue(HeaderProperty); }
        set { SetValue(HeaderProperty, value); }
    }
}

And style:

<Style TargetType="{x:Type local:HeaderedSeparator}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:HeaderedSeparator}">
                <Grid Height="{TemplateBinding Height}">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="15"/>
                        <ColumnDefinition Width="Auto"/>
                        <ColumnDefinition />
                    </Grid.ColumnDefinitions>
                    <Separator Grid.Column="0"/>
                    <TextBlock Grid.Column="1" 
                        VerticalAlignment="Center" Margin="5 0" 
                        Text="{TemplateBinding Header}"/>
                    <Separator Grid.Column="2" />
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

And then use it:

<local:HeaderedSeparator Header="Header1"/>
<local:HeaderedSeparator Header="Header2"/>
like image 116
Navid Rahmani Avatar answered Oct 18 '22 20:10

Navid Rahmani


Try something like this:

  <Grid Height="20">
     <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="*"/>
     </Grid.ColumnDefinitions>
     <Separator
        Width="20"
        VerticalAlignment="Center"/>
     <TextBlock
        Grid.Column="1"
        HorizontalAlignment="Center"
        Margin="4, 0"
        Text="My Header"/>
     <Separator
        Grid.Column="2"
        VerticalAlignment="Center"/>
  </Grid>
like image 2
Anvaka Avatar answered Oct 18 '22 20:10

Anvaka