[英]Accessing WPF UserControl child element property
Let's say I have a UserControl with several child controls假设我有一个带有多个子控件的 UserControl
<UserControl x:Class="Any.AnyControl"
<Grid>
<Label Name="label1" Background="Black" />
... more controls here
</Grid>
</UserControl>
and I use it in MainWindow like so:我在 MainWindow 中使用它,如下所示:
<Window>
<Grid>
<local:AnyControl/>
// I want to access AnyControl label1 Background property here
</Grid>
</Window>
I know how I can access AnyControl label1 Background property in code-behind, but is there any way I can access it in parent XAML?我知道如何在代码隐藏中访问 AnyControl label1 Background 属性,但是有什么方法可以在父 XAML 中访问它?
my code now: in parent XAML我现在的代码:在父 XAML 中
<local:AlertControl LabelBackground="Blue">
in UserControl在用户控件中
<Label Background="{Binding LabelBackground, RelativeSource={RelativeSource AncestorType=UserControl}}" />
and try with this too也试试这个
<Label Background="{Binding LabelBackground, RelativeSource={RelativeSource AncestorType=local:AlertControl}}" />
Try like this (although it's not the best practice to style controls in their parent control):像这样尝试(尽管在其父控件中设置控件样式不是最佳做法):
<local:AnyControl>
<local:AnyControl.Resources>
<Style TargetType="{x:Type Label}">
<Setter Property="Background" Value="Red" />
</Style>
</local:AnyControl.Resources>
</local:AnyControl>
It sets the background property for all controls of a given type inside your UserControl.它为 UserControl 中给定类型的所有控件设置背景属性。 If you want to change it for a control selected by a name, you can do something like that (change Value="Test"
to your control's name):如果您想为按名称选择的控件更改它,您可以执行类似操作(将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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.