访问 WPF UserControl 子元素属性

Accessing WPF UserControl child element property(访问 WPF UserControl 子元素属性)
本文介绍了访问 WPF UserControl 子元素属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Let's say I have a UserControl with several child controls

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

我在 MainWindow 中这样使用它:

and I use it in MainWindow like so:

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

我知道如何在代码隐藏中访问 AnyControl label1 背景属性,但有什么方法可以在父 XAML 中访问它吗?

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?

我现在的代码:在父 XAML 中

my code now: in parent XAML

<local:AlertControl LabelBackground="Blue">                           

在用户控件中

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

也试试这个

<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>

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

It sets the background property for all controls of a given type inside your 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):

<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>

这篇关于访问 WPF UserControl 子元素属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)