admin管理员组

文章数量:1129124

Working on an application that has areas, with different foreground color for each area.

Generic skeleton of the issue would look like this:

<Window Style={StaticResource GrayForeground}>
    <UniformGrid Rows="1">
       <Grid x:Name="defaultColor">
           <!-- Text elements here -->
       </Grid>
       <Grid x:Name="emphasisColor"
             TextElement.Foreground="Red">
           <!-- Text elements here -->
       </Grid>
    </UniformGrid>
</Window>

Where GrayForeground style is:

<Style x:Key="GrayForeground"
       TargetType="{x:Type Window}">
    <Setter Property="TextElement.Foreground"
            Value="Gray" />
</Style>

This works great for TextBlocks - foreground for those that reside inside of defaultColor grid is gray and those that reside in emphasisColor grid get red foreground.

Now I need to define a Label to allow me to do some formatting before setting the text for the TextBlock, so I created a style for the label:

<Style x:Key="LabelForNumbers"
       TargetType="{x:Type Label}">
    <Setter Property="ContentTemplate">
        <Setter.Value>
            <DataTemplate>
                <TextBlock>
                    <TextBlock.Text>
                        <!-- MultiBinding with converter to set correct formatting -->
                    </TextBlock.Text>
                </TextBlock>
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>

The problem:
All instances of Label have black foreground.
This is because default style for Label sets foreground to black.

The question:
Is there a way to unset the value for foreground so that Label will continue to propagate/inherit TextElement.Foreground property?


The only solution I can think of is adding this setter to the style of the label:

<Setter Property="Foreground">
    <Setter.Value>
        <PriorityBinding FallbackValue="Gray">
            <Binding Path="(TextElement.Foreground)"
                     RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType={x:Type FrameworkElement}}" />
            <Binding Path="Foreground"
                     RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType={x:Type FrameworkElement}}" />
        </PriorityBinding>
    </Setter.Value>
</Setter>

It seems to work, but feels "hacky" and not WPF-like.

本文标签: wpfUnsetting property value that was set in the default styleStack Overflow