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

自定义BindableProperty绑定失效问题排查

自定义ContentView绑定值不更新的问题与解决方法

在为自定义ContentView绑定值时遇到问题:ContentPage中使用了作为ContentView的AccountStatusView,它包含AccountStatusDto类型的BindableProperty,但绑定后该属性从未更新。以下是相关代码:

MainPage - XAML

<Grid>
    <controls:AccountStatusView AccountStatus="{Binding AccountStatus}" />
</Grid>

MainPage - C#

public partial class MainPage : ContentPage
{
    public MainPage(ViewModel vm) {
        BindingContext = vm;
        InitializeComponent();
    }
}

ViewModel

public partial class ViewModel : ObservableObject
{
    [ObservableProperty] private AccountStatusDto _accountStatus;
    // . . .
    public async Task InitializeAsync()
    {
        AccountStatus = await _repo.GetAccountStatus();
    }
}

AccountStatusView - C#

public partial class AccountStatusView : ContentView
{
    public static readonly BindableProperty AccountStatusProperty =
        BindableProperty.Create(nameof(AccountStatus), typeof(AccountStatusDto), typeof(AccountStatusView), propertyChanged: DoSomething);

    public static void DoSomething(BindableObject bindable, object oldvalue, object newvalue)
    {
        // do something with the new value
    }

    public AccountStatusDto AccountStatus
    {
        get => (AccountStatusDto)GetValue(AccountStatusProperty);
        set => SetValue(AccountStatusProperty, value);
    }

}

解决方案

找到的有效解决方法如下:

创建包含XAML的自定义组件时,请勿设置BindingContext = this;

另外,通过x:Name访问组件属性的方案也能解决问题:

为自定义组件设置x:Name,并将其作为绑定的Source:

<VerticalStackLayout
    ...
    x:Name="me"     <!-- 重要!可按需修改名称。 -->
    x:Class="DataBindingExample.Card">
    ...
    <Label Text="{Binding CardIncrement, Source={x:Reference me}}"
    ... 

该方案完美解决了问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 10:32:22