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

MAUI自定义控件绑定数据不显示,求排查问题原因

MAUI自定义控件TimeEntryCard绑定不显示问题修复

你的问题出在两个关键地方,以下是具体错误和修正方案:

错误1:BindableProperty创建参数错误

你定义DayProperty时,第一个参数传错了——应该传入CLR属性名Day,而非绑定属性本身的名称DayProperty。这个参数是用来关联绑定属性和对应的CLR属性的,参数错误会导致绑定系统无法正确识别关联关系。

错误代码:

public static readonly BindableProperty DayProperty = BindableProperty.Create(nameof(DayProperty), typeof(string), typeof(TimeEntryCard), string.Empty);

修正后代码:

public static readonly BindableProperty DayProperty = BindableProperty.Create(nameof(Day), typeof(string), typeof(TimeEntryCard), string.Empty);

错误2:XAML绑定未指定数据源

自定义控件的XAML中,Label的{Binding Day}默认会读取当前BindingContext,但ContentView的BindingContext默认继承自父容器,而非控件自身。需要明确指定绑定源为控件本身,有两种实现方式:

方式1:在构造函数中设置BindingContext为自身

直接在控件构造函数里将BindingContext指向自己,这样内部绑定会自动读取控件的属性:

public TimeEntryCard()
{
    InitializeComponent();
    BindingContext = this;
}

方式2:在XAML中使用RelativeSource指定绑定源

无需修改构造函数,直接在绑定表达式里指定源为当前控件类型:

<!-- 先在ContentView根节点添加本地命名空间引用 -->
<ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:OneCampus.Components"
             x:Class="OneCampus.Components.TimeEntryCard">

    <!-- 修改Label的绑定表达式 -->
    <Label Text="{Binding Day, RelativeSource={RelativeSource AncestorType={x:Type local:TimeEntryCard}}}" />
</ContentView>

完整修正示例(方式1)

后端代码

namespace OneCampus.Components;

public partial class TimeEntryCard : ContentView
{
    public static readonly BindableProperty DayProperty = BindableProperty.Create(nameof(Day), typeof(string), typeof(TimeEntryCard), string.Empty);

    public string Day
    {
        get => (string)GetValue(DayProperty);
        set => SetValue(DayProperty, value);
    }

    public TimeEntryCard()
    {
        InitializeComponent();
        BindingContext = this;
    }
}

前端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="OneCampus.Components.TimeEntryCard">

    <VerticalStackLayout>
        <Frame BackgroundColor="Blue" 
               HorizontalOptions="Fill">
            <HorizontalStackLayout Spacing="10">
                <Label Text="{Binding Day}" />
                <VerticalStackLayout>
                    <Label Text="{Binding InTime}" />
                    <Label Text="{Binding OutTime}" />
                </VerticalStackLayout>
                <Label Text="{Binding TotalTime}" />
            </HorizontalStackLayout>
        </Frame>
    </VerticalStackLayout>
    
</ContentView>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 16:17:17