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

.NET MAUI视图无法读取ViewModel数据——智能感知显示已连接

问题排查与解决

你的核心问题是未给ContentPage设置BindingContext——虽然通过x:DataType让智能感知识别了绑定类型,但视图并没有关联到具体的ViewModel实例,导致运行时无法读取数据。

解决方案一:在XAML中直接指定BindingContext

修改你的XAML代码,在ContentPage标签内添加BindingContext的声明:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:model="clr-namespace:MauiCalendar.Model"
         xmlns:viewmodel="clr-namespace:MauiCalendar.ViewModel"
         x:Class="MauiCalendar.View.DaySingleView"
         x:DataType="viewmodel:DaySingleViewModel"
         Title="{Binding Title}">

    <!-- 添加BindingContext声明 -->
    <ContentPage.BindingContext>
        <viewmodel:DaySingleViewModel />
    </ContentPage.BindingContext>

    <VerticalStackLayout>
        <Entry
            Text="{Binding Title}" />

        <Label 
            Text="{Binding Title}" />

        <Label
            Text="Test" />

        <Button
            Text="Load Days" />
    </VerticalStackLayout>
</ContentPage>

解决方案二:在后台代码中设置BindingContext

打开DaySingleView.xaml.cs,在构造函数中初始化BindingContext:

public DaySingleView()
{
    InitializeComponent();
    // 绑定到ViewModel实例
    BindingContext = new MauiCalendar.ViewModel.DaySingleViewModel();
}

补充说明

  • x:DataType仅用于编译时的绑定语法检查,帮助智能感知识别属性,但不会自动创建ViewModel实例或建立视图与模型的关联。
  • 两种方案任选其一即可,设置完成后运行,Entry和Label会显示"Starting Value",修改Entry文本时Label也会同步更新(CommunityToolkit.Mvvm的[ObservableProperty]已自动实现INotifyPropertyChanged接口)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 20:30:46