Pavel's Blog

Pavel is a software guy that is interested in almost everything software related... way too much for too little time

WPF’s Separator does not respect auto style

It’s something I came across, which seems like a bug to me. A WPF element can use a style automatically if the style uses the TargetType property set to the type of that element and there is no x:Key value. That is, there is no need for a (e.g. textual) key (the type is the key), and there is no need to specify a Style property for elements of that type.

For some reason, the Separator type, commonly found in menus and toolbars, does not respect it, and requires an explicit Style setting with an appropriate key.

For example, this piece of XAML should make the separator a red line.

<Style TargetType="Separator">

  <Setter Property="Template">

    <Setter.Value>

      <ControlTemplate TargetType="Separator">

         <Border Background="Red" />

      </ControlTemplate>

    </Setter.Value>

  </Setter>

</Style>

For this menu:

 

<Menu DockPanel.Dock="Top">

  <MenuItem Header="_File">

    <MenuItem Header="_Open..." />

    <Separator />

    <MenuItem Header="E_xit" />

  </MenuItem>

</Menu>

But it doesn’t. To make this work, I must add a style key and apply it:

<Style TargetType="Separator" x:Key="sep1">

  <Setter Property="Template">

    <Setter.Value>

      <ControlTemplate TargetType="Separator">

         <Border Background="Red" />

      </ControlTemplate>

    </Setter.Value>

  </Setter>

</Style>

<Menu DockPanel.Dock="Top">

  <MenuItem Header="_File">

    <MenuItem Header="_Open..." />

    <Separator Style="{StaticResource sep1}"/>

    <MenuItem Header="E_xit" />

  </MenuItem>

</Menu>

The result is:

image

Posted: Dec 02 2009, 01:46 PM by pavely | with 2 comment(s)
תגים:, , ,

Comments

Ran Trifon said:

You need to add to the style that specific key,

It will work with it.

<Style x:Key="{x:Static MenuItem.SeparatorStyleKey}"  TargetType="Separator">

  <Setter Property="Template">

    <Setter.Value>

       <ControlTemplate TargetType="Separator">

       <Border Background="Red"/>

     </ControlTemplate>

   </Setter.Value>

 </Setter>

</Style>

# December 3, 2009 10:51 AM

pavely said:

Thank you for that.

I guess the "default" way works when a separator is out of a menu altogether, although this is very uncommon.

# December 3, 2009 12:50 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: