首页 > 解决方案 > WPF - 如何从父元素中获取值?

问题描述

嗨,我正在尝试从 Button Content 传递到 ControlTemplate -> Label Content 我该怎么做?

我刚开始学习 xaml 并遇到这样的问题,我将非常感谢任何帮助。

代码:

    <Style x:Key="CloseBtn" TargetType="Button">
        <Setter Property="Content" Value="Flex"/> <!---From here --->
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Label Name="Border" Focusable="False" Background="#00ff0000" Foreground="#A770FA" 
    Content="" <--- Over here --->
     VerticalContentAlignment="Center" HorizontalContentAlignment="Center"/>
                    
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>```

标签: wpfxamlbuttonstylescontroltemplate

解决方案


在绑定中使用相对源绑定到父控件上的属性,在这种情况下,它可以是:


<Label Name="Border" Focusable="False" Background="#00ff0000" Foreground="#A770FA" 
    Content="{Binding RelativeSource={RelativeSource AncestorType={x:Type Button}},Path=Content}"
     VerticalContentAlignment="Center" HorizontalContentAlignment="Center"/>

OR

<Label Name="Border" Focusable="False" Background="#00ff0000" Foreground="#A770FA" 
    Content="{Binding RelativeSource={RelativeSource TemplatedParent},Path=Content}"
     VerticalContentAlignment="Center" HorizontalContentAlignment="Center"/>

相对源还允许您绑定到同一控件上的属性、祖先到某个级别等。请参阅文档:https://docs.microsoft.com/en-us/dotnet/api/system.windows。 data.relativesource?view=net-5.0


推荐阅读