Accessing WPF UserControl child element property

无人久伴 提交于 2019-12-30 15:42:24

问题


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>

and I use it in MainWindow like so:

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

my code now: in parent 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}}" />

回答1:


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


来源:https://stackoverflow.com/questions/46686211/accessing-wpf-usercontrol-child-element-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!