1
votes

So this particular answer seems to partially work: Reset inherited WPF style?

However, it doesn't seem to override styling on "inner" elements. For example, if I set the TextBlock Foreground to red in my main App.xaml file, it will change all TextBlock elements, but it will also impact controls that have inner/templated controls, like the text of a Button element.

When I try to override the style later, it impacts only the direct TextBlock elements. Buttons still seem to use the red text styling from the App.xaml.

In App.xaml:

<Application.Resources>
    <Style TargetType="{x:Type TextBlock}">
        <Setter Property="Foreground" Value="Red" />
    </Style>
</Application.Resources>

MainWindow.xaml contents (both controls show red text):

<StackPanel>
    <TextBlock>Hello World! I should be red!</TextBlock>
    <Button Click="Button_Click" Content="I'm red, too. Click me to open a new Popup!" />
</StackPanel>

The Button_Click event:

private void Button_Click(object sender, RoutedEventArgs e)
{
    var x = new Popup();
    x.Show();
}

And Popup.xaml:

<Window.Resources>
    <Style TargetType="{x:Type TextBlock}">
        <Setter Property="Foreground" Value="Blue" />
    </Style>
</Window.Resources>
<StackPanel>
    <TextBlock>Hello World, I'm blue!</TextBlock>
    <Button Content="Oh no! I should be blue, too, but I'm red!" />
</StackPanel>

The result: Screenshot showing the Popup window button having red text

How can I make the style within Popup.xaml have the same level of impact as the same style in App.xaml?

EDIT: I should note that the real underlying motivation here is that I build plugins for an enterprise app. The base app has a lot of styling that is carrying over into my plugins, and I'm trying to come up with a "reset all styles" resource dictionary, but when I have things like DataGrids, the content elements are not being reset - they're inheriting styles from the base app, and I'm trying to find an effective way of resetting them without being overly explicit.

1
Interestingly they both show up as black in the designer. - Neil B
Not really a duplicate. Similar, and has the same final answer, but the below answer with that article is much better. - jhilgeman

1 Answers

1
votes

I think this article explains what you are experiencing, and why the style inheritance takes a different precedence than you expect.

Here you can find the info about dependency property precedence.

As far as I know the only way to keep a general style like this from affecting sub elements is to explicitly style them. (Not a good approach)