0

我创建了一个ResourceDictionary文件来存储 aPage的背景颜色。接下来,我ResourceDictionary在我的主页中引用了它。

虽然 Visual Studio 2019 (16.7.7) 设计器正确地将Page的背景颜色呈现为红色,但正在运行的程序本身却没有。

Visual Studio 2019 - UWP

我究竟做错了什么?



以下是来源:

主页.xaml

<Page
    x:Class="Test1.MainPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d">
    <Page.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Dictionary1.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Page.Resources>
    <StackPanel>
        <TextBlock>
            Test
        </TextBlock>
    </StackPanel>
</Page>

Dictionary1.xaml

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

    <Style TargetType="Page">
        <Setter Property="Background" Value="Red" />
    </Style>
</ResourceDictionary>
4

2 回答 2

0

来自 Jim Walker @ https://github.com/MicrosoftDocs/windows-uwp/issues/2790#issuecomment-722065687

在您的应用程序中更改颜色的首选方法是轻量级样式,它通过使用相同的键创建您自己的画笔来覆盖控制使用的系统画笔。大多数控件的类文档都有一个可以覆盖的资源列表。

对于Page背景,您覆盖ApplicationPageBackgroundThemeBrush资源:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.ThemeDictionaries>
            <ResourceDictionary x:Key="Default">
                <SolidColorBrush x:Key="ApplicationPageBackgroundThemeBrush" Color="Red"/>
                <Style TargetType="TextBlock">
                    <Setter Property="Foreground" Value="Black"/>
                </Style>
            </ResourceDictionary>
        </ResourceDictionary.ThemeDictionaries>
    </ResourceDictionary>
</Application.Resources>

(因为它是ThemeResource,所以它需要在主题字典中。我使用带有键“Default”的字典来保持简单,但最好同时使用XAML中讨论的“Light”和“Dark”资源主题资源。)

这还假定页面背景设置为此资源,它在 Visual Studio 模板中默认设置,如下所示:Background="{ThemeResource ApplicationPageBackgroundThemeBrush}".

于 2020-11-06T02:37:53.077 回答
0

而不是导入资源字典,而是像这样Page导入此资源字典App.xaml

<Application
    x:Class="Test1.App">
    
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Dictionary1.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

然后你需要在x:Key你的自定义样式中添加一个:

<Style x:Key="CustomPageBackground" TargetType="Page">
    <Setter Property="Background" Value="Red" />
</Style>

现在,您Page只需添加以下行:

Style="{StaticResource CustomPageBackground}"

像这样:

<Page
    x:Class="Test1.MainPage"
    Style="{StaticResource CustomPageBackground}"
    ...>
    
    <!-- UI-elements -->
</Page>
于 2020-11-01T12:01:55.077 回答