WPF 将样式应用于用户控件的子控件

WPF Apply Style to Child Controls of a user control

我有一个 WPF 用户控件,其中有几个标签(动态创建)。我想从我的用户控件中设置这些标签的样式(每个标签都应该具有相同的样式)。

所以简单来说,设置用户控件的样式应该将该样式应用到它的所有标签。

在 UserControl.Resources 中,您可以设置如下内容:

<Style TargetType="Label">
     <Setter Property="Foreground" Value="#112233" />
</Style>

只要您不为样式提供 x:Key 元素,它就会应用于您的 UserControl 中的所有子标签。

可以在 UserControl 资源中为 Label 声明样式并将 Setters 值绑定到 UserControl 属性,例如:

<UserControl x:Class="WpfApplication3.UserControl1"
             x:Name="Uc1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <UserControl.Resources>
        <Style TargetType="Label">
            <Setter Property="Foreground"
                    Value="{Binding Foreground, ElementName=Uc1, Mode=OneWay}"/>
        </Style>
    </UserControl.Resources>

    <Grid>            
        <Label Content="123"/>
    </Grid>
</UserControl>

通过这种方式更改 UserControl 前景将影响内部的所有标签(如果它们不覆盖前景设置)

样式可以使用类型名称(Label)作为键,默认情况下会应用。或者它可以有一些其他键,应该明确分配给动态创建的标签