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

MAUI自定义控件绑定属性不更新问题求助

问题分析与解决方案

你的自定义控件实现思路是正确的,问题出在BindableProperty的propertyChanged回调中的错误代码,干扰了属性变更通知的正常传递。

错误原因

你在TitleChanged回调中写了control.Title = newValue as string;,这行代码完全多余且错误:

  • 当BindableProperty的值更新时,Title属性的get方法会自动从BindableProperty获取最新值,不需要手动赋值
  • 调用Title的set方法会再次触发SetValue,导致不必要的循环操作,打断了内部Label的绑定更新逻辑

修正后的代码

C#代码

public partial class BindTest : ContentView
{
    public static readonly BindableProperty TitleProperty = BindableProperty.Create(
        nameof(Title), 
        typeof(string), 
        typeof(BindTest), 
        string.Empty);

    public string Title
    {
        get => (string)GetValue(TitleProperty);
        set => SetValue(TitleProperty, value);
    }

    public BindTest()
    {
        InitializeComponent();
    }
}

XAML代码(无需修改)

<?xml version="1.0" encoding="utf-8" ?>
<ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MauiDemo.BindTest" x:Name="this">
    <StackLayout BindingContext="{x:Reference this}">
        <Label TextColor="White" Text="{Binding Title}" />
    </StackLayout>
</ContentView>

验证说明

修正后,外部页面的绑定逻辑保持不变即可:

<controls:BindTest Title="{Binding TestString}"/>
<Label Text="{Binding TestString}"/>

当ViewModel中的TestString更新时,自定义控件内的Label会和普通Label一样同步显示最新值——因为Title作为BindableProperty,会自动向内部绑定传递属性变更通知。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 16:15:48