Daniel
Daniel

Reputation: 1124

Add setters to Control's style without breaking ControlTemplate

I have global template for the progress bar, but on one I have to bind it's color to another element's state. It seems that if I change ProgressBar's style that it looses ControlTemplate. What am I missing here?

<Style TargetType="ProgressBar">           
<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="ProgressBar">
            <Border Name="PART_Track" ... Background="{TemplateBinding Background}"  >
                <Rectangle Name="PART_Indicator" ... Fill="{TemplateBinding Foreground}" />
            </Border>
        </ControlTemplate>
    </Setter.Value>
</Setter>

<ProgressBar x:Name="PBar" Background="#d8d8d8">
<ProgressBar.Resources>
    <Style TargetType="{x:Type ProgressBar}" >
        <Setter Property="Foreground" Value="#6CC655"/>
        <Style.Triggers>
            <DataTrigger Binding="{Binding IsChecked, ElementName=toggleX, Mode=OneWay}" Value="True">
                <Setter Property="Foreground" Value="#FFFFFF"/>
            </DataTrigger>
        </Style.Triggers>-->
    </Style>
</ProgressBar.Resources>

Upvotes: 3

Views: 379

Answers (2)

SuperJMN
SuperJMN

Reputation: 14002

In my opinion, you should use 2 different styles:

One is the generic one. The other is the more specific style.

THE GENERIC:

<Style TargetType="{x:Type ProgressBar}">           
   <Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="{x:Type ProgressBar}">
            <Border Name="PART_Track" ... Background="{TemplateBinding Background}"  >
                <Rectangle Name="PART_Indicator" ... Fill="{TemplateBinding Foreground}" />
            </Border>
        </ControlTemplate>
    </Setter.Value>
</Setter>

THE SPECIFIC:

<Style TargetType="{x:Type ProgressBar}" BasedOn="{StaticResource {x:Type ProgressBar}}">        
   <Setter Property="Foreground" Value="#6CC655"/>  
   <Style.Triggers>
        <DataTrigger Binding="{Binding IsChecked, ElementName=toggleX, Mode=OneWay}" Value="True">
            <Setter Property="Foreground" Value="#FFFFFF"/>
        </DataTrigger>
    </Style.Triggers>
</Setter>

This should work. The point here is to use Style inheritance correctly since one is "based on" another. This way, things shouldn't break 😊

Upvotes: 1

Rohit Vats
Rohit Vats

Reputation: 81333

You can inherit default style using BasedOn. This way you will get all properties defined in base style including ControlTemplate:

<ProgressBar.Resources>
    <Style TargetType="{x:Type ProgressBar}"
           BasedOn="{StaticResource {x:Type ProgressBar}}">
    ....
</ProgressBar.Resources>

Upvotes: 2

Related Questions