chuckp
chuckp

Reputation: 313

WPF Button ... Is there a way to set a background color separately from a Style declaration

I have 50 buttons on a page, so I declared a Style that would declare a border and IsPressed behavior that applies to ALL buttons.

<UserControl.Resources>
    <statusModule:BooleanToBackgroundColorConverter x:Key="BooleanToBackgroundColor"/>
    <Style x:Key="ValveButtonStyle" TargetType="Button">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Border Name="border" Background="Transparent" BorderThickness="1" BorderBrush="Black">
                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="Button.IsPressed" Value="True">
                            <Setter TargetName="border" Property="BorderThickness"  Value="3" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</UserControl.Resources>

The issue I have is that EACH button background color is controlled via a separate ViewModel property, such as

 <Button Content="Deflection Gas Valve" Background="{Binding Path=OpenDeflectionGasValve, Converter={StaticResource BooleanToBackgroundColor}, Mode=OneWay}"  Style="{StaticResource ValveButtonStyle}"
 <Button Content="Purge Gas Valve" Background="{Binding Path=OpenPurgeGasValve, Converter={StaticResource BooleanToBackgroundColor}, Mode=OneWay}"  Style="{StaticResource ValveButtonStyle}"

and another button background binding would be to a completely different ViewModel property.

If I assign a Style to the button, then the Background setting as declared above has no effect.

Is there a way that I can use a Style for ALL buttons but declare a Background value as shown above for each.

Upvotes: 0

Views: 1648

Answers (1)

dovid
dovid

Reputation: 6472

in your ConroleTemplate, you need respect the original Background property of the TextBox control, via TemplateBinding. Each TextBox property (of apparance) that is not mentioned in your template becomes meaningless.

so change

Background="Transparent"

to:

Background="{TemplateBinding Background}"

Now, the background will be affected by the value in the background TextBox property. and for set default value to background property, set the color in the style via setter:

<Setter Property="Background" Value="Transparent" />

Upvotes: 1

Related Questions