基于父样式的WPF样式

基于父样式的WPF样式,wpf,xaml,Wpf,Xaml,假设我有一个容器元素(如网格)的WPF样式,它自动将样式应用于其子项,如下所示: <Window.Resources> <Style TargetType="Grid" x:Key="FormStyle"> <Style.Resources> <Style TargetType="Label"> <Setter Property="FontSize" Value=

假设我有一个容器元素(如网格)的WPF样式,它自动将样式应用于其子项,如下所示:

<Window.Resources>
    <Style TargetType="Grid" x:Key="FormStyle">
        <Style.Resources>
            <Style TargetType="Label">
                <Setter Property="FontSize" Value="50"/>
            </Style>
        </Style.Resources>
    </Style>
</Window.Resources>
那么一切都好了

我当然可以只命名样式,但肯定有一种更简单/不太冗长的方式


谢谢

以下是静态资源的查找过程:

  • 查找过程在资源中检查请求的密钥 由设置属性的元素定义的字典

  • 然后,查找过程将逻辑树向上遍历到 父元素及其资源字典。这一进程仍在继续 直到到达根元素

  • 已检查应用程序资源。应用程序资源是指应用程序中的资源 由应用程序对象定义的资源字典 用于您的WPF应用程序

  • 在您的案例中,要解析
    BasedOn=“{StaticResource{x:Type Label}”
    WPF首先查找
    Grid
    内部定义的
    ResourceDictionary
    ,然后查找
    窗口
    —网格的逻辑父级—及其
    资源,最后查找应用程序级资源。由于样式是
    FormStyle
    中的嵌套样式,WPF在任何地方都找不到它,默认为基本样式

    进一步了解上的静态资源查找行为

    要获得所需的输出,您可以:

    1) 将您的
    标签
    样式移出
    表单样式
    并移入
    窗口。Resources

    2) 将
    FormStyle
    中的标签样式合并到
    Grid
    元素中定义的标签样式中

    <Grid Style="{StaticResource FormStyle}">
        <Grid.Resources>
            <Style TargetType="Label">
                <Setter Property="Foreground" Value="Red"/>
                <Setter Property="FontSize" Value="50"/>
            </Style>
        </Grid.Resources>
        <Label Content="Blah"/>
    </Grid>
    

    非常感谢,非常有帮助。移动到窗口/网格有点挫败了这一点,因为它是一种应用程序级风格,由多个窗口/控件使用(我没有提到这一点)。第三点很好
    <Style TargetType="Label">
        <Setter Property="FontSize" Value="50"/>
    </Style>
    
    <Grid Style="{StaticResource FormStyle}">
        <Grid.Resources>
            <Style TargetType="Label">
                <Setter Property="Foreground" Value="Red"/>
                <Setter Property="FontSize" Value="50"/>
            </Style>
        </Grid.Resources>
        <Label Content="Blah"/>
    </Grid>
    
    <Window.Resources>
        <Style TargetType="Grid" x:Key="FormStyle">
            <Setter Property="Label.FontSize" Value="50"/>
        </Style>
    </Window.Resources>