You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

替换TemplateBinding为{x:Bind}时遇‘无法解析Background’错误求助

问题:ControlTemplate中用{x:Bind}替换TemplateBinding报错Unable to resolve symbol 'Background'

根据MSDN文档说明,从Windows 10版本1809开始,可在ControlTemplate中所有使用TemplateBinding的位置替换为{x:Bind}标记扩展。但定义自定义控件local:PomodoroTimer的样式时,将TemplateBinding替换为{x:Bind}后出现错误:Unable to resolve symbol 'Background',请问遗漏了什么?

代码示例

<Style TargetType="local:PomodoroTimer" >
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:PomodoroTimer">
                <Grid Width="300" Height="300" Background="{x:Bind Background}">
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

解决方案

  • {x:Bind}默认的绑定上下文是页面/用户控件的代码后台,而非ControlTemplate的目标控件。直接写{x:Bind Background}会去当前页面后台查找Background属性,自然找不到对应符号。
  • 要让{x:Bind}指向ControlTemplate的目标控件(即local:PomodoroTimer实例),需显式指定RelativeSource为TemplatedParent,同时设置Mode=OneWay(和TemplateBinding的默认行为一致)。

修改后的绑定代码:

Background="{x:Bind Background, RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay}"

简单来说,TemplateBinding是{x:Bind}的语法糖,它默认就关联TemplatedParent且为单向绑定,替换时不能省略这些关键参数,必须显式声明才能匹配原TemplateBinding的行为。


内容的提问来源于stack exchange,提问作者qanpi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 18:45:48