DCSIMG
December 2009 - Posts - Pavel's Blog
Sign in | Join | Help

Pavel's Blog

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

December 2009 - Posts

WPF’s Separator does not respect auto style

Published at Dec 02 2009, 01:46 PM by pavely

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