访问 WPF 用户控件 child 元素 属性

Accessing WPF UserControl child element property

假设我有一个带有多个 child 控件的 UserControl

<UserControl x:Class="Any.AnyControl"
    <Grid>
        <Label Name="label1" Background="Black" />
        ... more controls here  
    </Grid>
</UserControl>

我在 MainWindow 中这样使用它:

<Window>
    <Grid>
         <local:AnyControl/>
         // I want to access AnyControl label1 Background property here 
    </Grid>
</Window>

我知道如何在 code-behind 中访问 AnyControl label1 Background 属性,但是有什么方法可以在 parent XAML 中访问它?

我现在的代码: 在 parent XAML

<local:AlertControl LabelBackground="Blue">                           

在用户控件中

  <Label Background="{Binding LabelBackground, RelativeSource={RelativeSource AncestorType=UserControl}}" />

也试试这个

<Label Background="{Binding LabelBackground, RelativeSource={RelativeSource AncestorType=local:AlertControl}}" />

像这样尝试(尽管在父控件中设置控件的样式不是最佳做法):

<local:AnyControl>
    <local:AnyControl.Resources>
        <Style TargetType="{x:Type Label}">
            <Setter Property="Background" Value="Red" />
        </Style>
    </local:AnyControl.Resources>
</local:AnyControl>

它为 UserControl 中给定类型的所有控件设置背景 属性。如果您想为通过名称选择的控件更改它,您可以执行类似的操作(将 Value="Test" 更改为您的控件名称):

<local:AnyControl>
    <local:AnyControl.Resources>
        <Style TargetType="{x:Type Label}">
            <Style.Triggers>
                <Trigger Property="Name" Value="Test">
                    <Setter Property="Background" Value="Red" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </local:AnyControl.Resources>
</local:AnyControl>