Nuts
Nuts

Reputation: 2813

TextBlock foreground binding to IsEnabled

I wonder why is not the below Style changing the TextBlock Foreground color whenver Checkbox IsChecked status changes

<CheckBox Name="checkbox" IsChecked="True"/>

<TextBlock Foreground="LightGray" IsEnabled="{Binding ElementName=checkbox, Path=IsChecked}">
     <TextBlock.Style>
           <Style TargetType="TextBlock">
                 <Style.Triggers>
                       <Trigger Property="TextBlock.IsEnabled" Value="False">
                            <Setter Property="TextBlock.Foreground" Value="Gray" />
                       </Trigger>
                  </Style.Triggers>
            </Style>
      </TextBlock.Style>
 </TextBlock>

Upvotes: 3

Views: 2800

Answers (2)

123 456 789 0
123 456 789 0

Reputation: 10865

Update your existing style and add a default property value on the style of your TextBlock

<TextBlock Foreground="LightGray" IsEnabled="{Binding ElementName=checkbox, Path=IsChecked}">
     <TextBlock.Style>
           <Style TargetType="TextBlock">
                 <Style.Triggers>
                       <Trigger Property="IsEnabled" Value="False">
                            <Setter Property="Foreground" Value="Gray" />
                       </Trigger>
                  </Style.Triggers>
            </Style>
           <Setter Property="Foreground" Value="Black"/>
      </TextBlock.Style>
 </TextBlock>

Upvotes: 0

Rohit Vats
Rohit Vats

Reputation: 81253

You have set local value that will always hold precedence over style triggers. Move the property declaration within style and it will work because style triggers have higher precedence than style setters.

<TextBlock IsEnabled="{Binding ElementName=checkbox, Path=IsChecked}">
    <TextBlock.Style>
        <Style TargetType="TextBlock">
            <Setter Property="Foreground" Value="LightGray"/> <-- HERE
            <Style.Triggers>
                <Trigger Property="TextBlock.IsEnabled" Value="False">
                    <Setter Property="TextBlock.Foreground" Value="Gray" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock>

Read on - Dependency Property Value Precedence.

Upvotes: 7

Related Questions