如果没有给定 x:Key,样式设置器将无法工作

Posted

技术标签:

【中文标题】如果没有给定 x:Key,样式设置器将无法工作【英文标题】:Style Setter doesn't work without given x:Key 【发布时间】:2021-11-13 07:28:55 【问题描述】:

如果 TargetType 设置为 ListBox,它可以工作。 但我想在 ListBox 中将 TargetType 设置为 TextBlock。 我知道我可以使用 x:Key ,但是为什么没有给定 x:Key 就不能工作??

<Window x:Class="WpfApp6.DataTemplatesLab"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp6"
        mc:Ignorable="d"
        Title="DataTemplatesLab" Height="450" Width="800">

    <Window.Resources>
        <SolidColorBrush x:Key="DataColor" Color="Firebrick"/>

        <Style TargetType="TextBlock">
            <Setter Property="FontSize" Value="28"/>
            <Setter Property="Background" Value="Cyan"/>
        </Style>
        
    </Window.Resources>

    <ListBox x:Name="ListPersonals" Width="600">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="2*"/>
                        <RowDefinition Height="*"/>
                        <RowDefinition Height="*"/>
                        <RowDefinition Height="*"/>
                    </Grid.RowDefinitions>
                    <TextBlock Text="Binding Name" Grid.Row="0"  />
                    <TextBlock Text="Binding Gender" Grid.Row="1" />
                    <TextBlock Text="Binding Email" Grid.Row="2" />
                    <TextBlock Text="Binding Title" Grid.Row="3"  />
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Window>

【问题讨论】:

【参考方案1】:

您需要使用键或在 DataTemplate 级别定义样式。

        <ListBox x:Name="ListPersonals" Width="600" ItemsSource="Binding DemoCollection">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <DataTemplate.Resources>
                        <Style TargetType="TextBlock" BasedOn="StaticResource x:Type TextBlock" />
                    </DataTemplate.Resources>

这是因为 DataTemplates 作为封装边界工作。这意味着任何基于 TargetType 的样式查找都会在 DataTemplate 处停止。

请注意,App.xaml 中定义的样式是此规则的一个例外。如果您要在 app.xaml 中定义样式资源,则样式将应用于内部控件,即使没有在 DataTemplate 中重新定义它们

【讨论】:

以上是关于如果没有给定 x:Key,样式设置器将无法工作的主要内容,如果未能解决你的问题,请参考以下文章

如果样式已经设置,如何覆盖 WPF 子控件样式?

如何为表格中的一行设置样式?

如何覆盖全局样式(没有 x:Key),或者将命名样式应用于所有以类型为目标的控件?

样式在组件中无法正常工作?

以编程方式插入的按钮样式无法正常工作

样式 JSX 无法与 NextJS 中的 @media-query 一起正常工作