WPF - 如何从父元素获取值?

问题描述

嗨,我正在尝试从按钮内容传递到 ControlTemplate -> 标签内容 我该怎么做?

我刚开始学习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>```

解决方法

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


<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