我创建了一个ResourceDictionary
文件来存储Page
的背景色。接下来,我在主页上引用了ResourceDictionary
。
虽然Visual Studio 2019(16.7.7)设计器正确地将Page
的背景颜色呈现为红色,但是运行的程序本身却没有。
我在做什么错了?
<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>
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Style TargetType="Page">
<Setter Property="Background" Value="Red" />
</Style>
</ResourceDictionary>
答案 0 :(得分: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>
答案 1 :(得分:0)
来自Jim Walker @ https://github.com/MicrosoftDocs/windows-uwp/issues/2790#issuecomment-722065687:
更改应用程序颜色的首选方法是lightweight styling,该方法通过使用相同的键创建自己的画笔来覆盖控制使用的系统画笔。大多数控件的类文档都有一个您可以覆盖的资源列表。
对于
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”键,但最好同时使用“ Light”和“ XAML theme resources中讨论的“黑暗”资源。)
这还假定页面背景已设置为该资源,在Visual Studio模板中默认为该资源,例如:
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
。