Hussein Khalil
Hussein Khalil

Reputation: 1625

Changing a label's foreground color using style triggers

I created a style for a Label which is supposed to change the color of the foreground depending on the value of the "IsEnabled" property:

<Style x:Key="ToggleLabelStyle" TargetType="{x:Type Label}">
    <Style.Triggers>
        <Trigger Property="IsEnabled" Value="False">
            <Setter Property="Foreground" Value="{DynamicResource DisabledToggleTextBrush}"/>
        </Trigger>
    </Style.Triggers>
   (...)
</Style>

One of my controls has a label with this style applied. The "IsEnabled" property of the label is bound to a property in the control's View-Model:

View's XAML:

<Label x:Name="RememberCredentialsLabel" Style="{DynamicResource ToggleLabelStyle}" IsEnabled="{Binding SaveCredentials}" Content="Remember Credentials" Grid.Column="1" Margin="0,28.849,39.339,10.124" Grid.Row="3" HorizontalAlignment="Right" Width="130.5" Foreground="White"/>

View-Model Property:

public bool SaveCredentials
{
    get
    {
        return _saveCredentials;
    }
    set
    {
        _saveCredentials = value;
        RaisePropertyChanged(() => SaveCredentials);
    }
}

The property is properly bound, and the control is alerted when its value changes. The problem is, the color of the label's foreground never changes. I tried hard-coding a value for the Foreground in the style (ex: Red), but it still doesn't change.

As a last resort, I tried changing the visibility status of the control to Hidden instead of changing the foreground's value and it worked. The label would hide and display itself accordingly.

Why am I unable to change the value of the foreground from within a trigger in a style ?

I'm using Expression Blend 4 as well as editing the code manually. I'm also using PRISM 4.

Upvotes: 0

Views: 4128

Answers (2)

brunnerh
brunnerh

Reputation: 185280

You must not set the Forground on the Label itself, the local value will override the style trigger due to precedence. The trigger thus does not affect the Foreground.

Setters can be overriden by triggers though, so you could move the value into a style setter.

Upvotes: 4

Tigran
Tigran

Reputation: 62265

Just guess:

To me is seems that in Label definition Foreground="White" should be removed, as it overcome the style definition. Instead this add

<Trigger Property="IsEnabled" Value="True">
       <Setter Property="Foreground" Value="White"/>
   </Trigger>

Should work...

Upvotes: 1

Related Questions