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

自定义TemplatedView的BindableProperty绑定TemplateBinding失效怎么办?

解决Xamarin.Forms中TemplatedView自定义控件的TemplateBinding问题

嘿,我来帮你搞定这个绑定问题!你的核心问题出在TemplateBinding的写法上——在ControlTemplate内部,完全不需要通过Parent来引用自定义控件的属性,因为TemplateBinding默认的绑定源就是当前使用该模板的TemplatedView实例(也就是你的MyButton)。

问题根源

你写的BackgroundColor="{TemplateBinding Parent.BGCol}"是错误的:这里的Parent指向的是Grid的直接父元素(而非你的MyButton控件),自然找不到BGCol属性,绑定也就失效了。

修复方案

1. 修正ControlTemplate中的绑定写法

直接把Grid的BackgroundColor绑定改成引用BGCol即可,不需要额外的Parent前缀:

<Grid x:Name="MyGrid" Grid.Row="1" ColumnSpacing="0" BackgroundColor="{TemplateBinding BGCol}">

2. 优化BindableProperty定义(可选但推荐)

你的后台代码定义BindableProperty是有效的,但用nameof(BGCol)代替硬编码字符串,能避免拼写错误,让代码更健壮:

public static readonly BindableProperty BGColProperty = BindableProperty.Create(
    nameof(BGCol), 
    typeof(Color), 
    typeof(MyButton), 
    Color.Orange);

3. 完整修复后的XAML示例

<?xml version="1.0" encoding="UTF-8"?>
<TemplatedView xmlns="http://xamarin.com/schemas/2014/forms" 
               xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
               xmlns:control="clr-namespace:Core.View.Control" 
               x:Class="Core.View.Control.MyButton">
    <TemplatedView.Resources>
        <ResourceDictionary>
            <ControlTemplate x:Key="MyButtonTemplate">
                <Grid BackgroundColor="Teal">
                    <!-- 其他无关内容 -->
                    <Grid x:Name="MyGrid" Grid.Row="1" ColumnSpacing="0" BackgroundColor="{TemplateBinding BGCol}">
                        <!-- 现在绑定应该能正常工作了 -->
                    </Grid>
                </Grid>
            </ControlTemplate>
            <Style TargetType="TemplatedView" x:Key="MyButtonStyle">
                <Setter Property="ControlTemplate" Value="{StaticResource MyButtonTemplate}" />
            </Style>
        </ResourceDictionary>
    </TemplatedView.Resources>
</TemplatedView>

额外说明

  • 在ControlTemplate内部使用TemplateBinding时,它会自动关联到承载该模板的TemplatedView的属性,无需手动指定绑定源。
  • 如果后续需要双向绑定场景,可以写成{TemplateBinding BGCol, Mode=TwoWay},不过对于BackgroundColor这类属性,单向绑定就足够了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:19:11