You need to enable JavaScript to run this app. WPF:如何在Button的ControlTemplate中获取父元素Content并赋值给Label
优惠活动
大模型
产品
解决方案
定价
更多

WPF:如何在Button的ControlTemplate中获取父元素Content并赋值给Label

Button内容向ControlTemplate内Label传递的实现方案

要实现外层Button的Content值同步到ControlTemplate内部Label的Content上,只需要在模板内部为Label的Content属性添加模板绑定,关联Button的对应属性即可。

修改后的完整样式代码

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

关键说明

  • 核心改动是将原Label中为空的Content="",替换为Content="{TemplateBinding Content}"。TemplateBinding是专门为ControlTemplate设计的轻量绑定,会自动将模板内元素的属性,与模板应用目标(即当前样式对应的Button)的同属性值同步——样式中默认设置的"Flex"会正常渲染在Label中。
  • 该绑定方式支持自定义覆盖:后续给使用该样式的Button单独设置不同的Content时,自定义内容也会自动同步到内部Label上,不会被样式的默认值强制覆盖。
  • 原代码中Label的Name取值为Border虽然不影响运行,但和内置控件类型重名,后续维护时容易混淆,建议替换为语义清晰的名称(如ContentLabel)。
  • 如果需要更高的绑定灵活性(例如Content承载复杂控件元素),也可以使用等效的相对源绑定写法替代TemplateBinding:Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content}"。

内容的提问来源于stack exchange,提问作者Mr. Demontino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.11 05:06:03