问题
No matter where I put my resources, their value isn't used:

The TextBlock text should be rendered black, but it's always rendered white.
Why?
Here is the source:
<Page
x:Class="TemplateTest.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" Background="Lavender">
<Page.Resources>
<Style TargetType="TextBlock">
<Setter Property="Foreground" Value="Black" />
</Style>
</Page.Resources>
<StackPanel>
<ListView>
<ListView.HeaderTemplate>
<DataTemplate>
<TextBlock>
<Run>Test</Run>
<Run>!</Run>
</TextBlock>
</DataTemplate>
</ListView.HeaderTemplate>
<ListView.ItemTemplate>
<DataTemplate x:DataType="x:String">
<TextBlock Text="{x:Bind}"></TextBlock>
</DataTemplate>
</ListView.ItemTemplate>
<x:String>Number 1</x:String>
<x:String>Number 2</x:String>
<x:String>Number 3</x:String>
</ListView>
</StackPanel>
</Page>
回答1:
Use x:key and provide a name to it and then refrence that name using staticresource in textblock:
<Page
x:Class="TemplateTest.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" Background="Lavender">
<Page.Resources>
<Style TargetType="TextBlock" x:Key="tbstyle">
<Setter Property="Foreground" Value="Black" />
</Style>
</Page.Resources>
<StackPanel>
<ListView>
<ListView.HeaderTemplate>
<DataTemplate>
<TextBlock Style={StaticResources tbstyle}>
<Run>Test</Run>
<Run>!</Run>
</TextBlock>
</DataTemplate>
</ListView.HeaderTemplate>
<ListView.ItemTemplate>
<DataTemplate x:DataType="x:String">
<TextBlock Text="{x:Bind}" Style={StaticResources tbstyle}></TextBlock>
</DataTemplate>
</ListView.ItemTemplate>
<x:String>Number 1</x:String>
<x:String>Number 2</x:String>
<x:String>Number 3</x:String>
</ListView>
</StackPanel>
</Page>
回答2:
From Jim Walker @ https://github.com/MicrosoftDocs/windows-uwp/issues/2790#issuecomment-722065687 :
TextBlockis different from most controls in that it doesn't have an editable template, so, unfortunately, it doesn't support lightweight styling. You have to use aStyleto set the foreground. And, as we already know, a Page- or App-level implicit style won't be applied toTextBlocks inside aDataTemplate, so you have to use a separate implicitStyleinside theDataTemplateor aStylewith a key to change thoseTextBlocks . As far as I know, there isn't any way around this.
来源:https://stackoverflow.com/questions/64637614/why-are-resources-not-used-in-this-page