TableCreek
TableCreek

Reputation: 799

Custom themed controls declared in base page

I have some Styles-Files.

For example ButtonStyles.xaml looks like this:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Style
        x:Key="CustomButtonStyle"
        TargetType="Button">

        <Setter
            Property="Foreground"
            Value="White" />

        <Setter
            Property="Background"
            Value="Black" />

        <Setter
            Property="Height"
            Value="32" />

    </Style>

    <Style
        TargetType="Button"
        BasedOn="{StaticResource CustomButtonStyle}">

    </Style>
</ResourceDictionary>

And I have Pages which extend from my BasePage. If I want my new Styles to override the controls I have to add this Code in every Page:

<Page.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="../Styles/ButtonStyles.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Page.Resources>

However if I have this code in my BasePage it won't theme my controls.

Is there a way to import my styles in every Page without copy-pasting this code over and over?

Upvotes: 0

Views: 39

Answers (1)

Jay Zuo
Jay Zuo

Reputation: 15758

I can't reproduce this issue with using BasePage in my side. It would be better if you can post a sample that can reproduce your issue.

However, to use the custom styles in every page, I recommend merging resource dictionaries into Application.Resources. Application.Resources is the best place to put any app-specific resources that are referenced by multiple pages in your app's navigation structure. If the requested resource is not found in the Page.Resources, the XAML resources system will tries to check the Application.Resources property. So if we merged resource dictionaries into Application.Resources, we can use them in all pages of the app. And if we want to use some different styles in certain pages, we can specify new Style in their Page.Resources. For more information, see Lookup behavior for XAML resource references.

So we can merge resource dictionaries into Application.Resources like following:
(Note that ../Styles/ButtonStyles.xaml can't be used in WinRT XAML, we should use "/" to refer to the package root.)

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/Styles/ButtonStyles.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

Then in other pages, if we don't specify the Style for Button, it will use the style defined in ButtonStyles.xaml.

Upvotes: 1

Related Questions