Search code examples
wpfstyles

Is it possible to style a BulletDecorator in WPF?


Obviously it can have a style applied to it - what am trying to find out if its possible to define the Bullet element within the style, so you don't have to keep defining it over and over in the XAML

<BulletDecorator>
       <BulletDecorator.Bullet>
            ...my bullet UIElement here...
        </BulletDecorator.Bullet>
        <TextBlock>
            ... my text here...
        </TextBlock>
</BulletDecorator> 

Solution

  • BulletDecorator.Bullet cannot be styled, and BulletDecorator is not a Control so it can't be templated.

    However you can get the effect in pure XAML by defining a ControlTemplate for ContentControl like this:

    <ControlTemplate x:Key="BulletTemplate" TargetType="{x:Type ContentControl}">
      <BulletDecorator>
        <BulletDecorator.Bullet>
          ...my bullet UIElement here...
        </BulletDecorator.Bullet>
        <ContentPresenter />
      </BulletDecorator>
    </ControlTemplate>
    

    Now you can use it like this:

    <ContentControl Template="{StaticResource BulletTemplate}">
      <TextBlock />
    </ContentControl>
    

    If you only use it a few times, the "<ContentControl Template=..." technique works fine. If you are going to use it more often, you can define a MyBullet class:

    public class MyBullet : ContentControl
    {
      static MyBullet()
      {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyBullet), new FrameworkPropertyMetadata(typeof(MyBullet));
      }
    }
    

    then move your ControlTemplate into Theme/Generic.xaml (or a dictionary merged into it) and wrap it with this:

    <Style TargetType="{x:Type local:MyBullet}">
      <Setter Property="Template">
        <Setter.Value>
          <ControlTemplate
            ...
        </Setter.Value>
      </Setter>
    </Style>
    

    If you do this, you can use:

    <local:MyBullet>
      <TextBox />
    </local:MyBullet>
    

    anywhere in your application.