DChi Shaggy
DChi Shaggy

Reputation: 22

How do I inherit a named style from App.xaml?

To help my WPF application have a similar feel, I have started using styles at the Application level:

<Application x:Class="MyApplication.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         StartupUri="MainWindow.xaml">
<Application.Resources>
    <Style TargetType="Button">
        <Setter Property="Margin" Value="10"/>
        <Setter Property="Padding" Value="5"/>
        <Setter Property="MinWidth" Value="60"/>
    </Style>

    <Style TargetType="TextBox">
        <Setter Property="Margin" Value="10"/>
        <Setter Property="Padding" Value="5"/>
        <Setter Property="MinWidth" Value="60"/>
        <Setter Property="VerticalAlignment" Value="Center"/>
    </Style>

    <Style TargetType="TextBlock">
        <Setter Property="Margin" Value="10"/>
        <Setter Property="Padding" Value="5"/>
        <Setter Property="MinWidth" Value="60"/>
        <Setter Property="VerticalAlignment" Value="Center"/>
    </Style>
</Application.Resources>

Now this works nice for of most my controls, but I would like to go a little deeper and add specific style types for things like headers. From each window I have done this:

<Window x:Class="myApp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="150" Width="300">
<Window.Resources>
    <Style x:Key="HeaderStyle" TargetType="TextBlock">
        <Setter Property="Foreground" Value="Gray" />
        <Setter Property="FontSize" Value="24" />
    </Style>
</Window.Resources>
<StackPanel>
    <TextBlock Style="{StaticResource HeaderStyle}">Header 1</TextBlock>
    <TextBlock >Some content</TextBlock>
</StackPanel>

How can I do that from App.xaml? To keep from having to touch every window if I want to change the formatting.

I feel like I would start by adding the same Style x:Key that worked in the window to the App. Then add this to the window

xmlns:app="clr-namespace:myApp"

If this is right, I'm not sure where to go from here. Here is one of my shots i the dark trying to make it work

<TextBlock Style="{x:Type app:HeaderTextBlock}">Header 1</TextBlock>

Thanks for any advice.

Upvotes: 0

Views: 176

Answers (1)

ganchito55
ganchito55

Reputation: 3607

The problem that you have here: <TextBlock Style="{x:Type app:HeaderTextBlock}">Header 1</TextBlock> is that you are trying to add a reference to the App.xaml, however you don't have to do it.

You can use this code <TextBlock Style="{StaticResource HeaderStyle}">Header 1</TextBlock>

Upvotes: 1

Related Questions