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

.NET MAUI中Picker绑定ViewModel后无选项显示问题求助

问题分析与解决方案

你的Picker控件未显示选项的核心原因是数据绑定目标为方法而非属性,.NET MAUI的数据绑定系统仅能识别属性,无法直接绑定到方法。以下是具体修复步骤:

1. 修改ViewModel:将方法转为属性

把ViewModel里的GetConditions()方法改写为只读属性,推荐两种实现方式:

方式一:使用ObservableProperty(社区工具包推荐)

using CommunityToolkit.Mvvm.ComponentModel;
using System.Collections.Generic;

namespace PlumbingCompany.Data
{
    public partial class Page7ViewModel : ObservableObject
    {
        public Page7ViewModel()
        {
            Conditions = new List<string>
            {
                "Yes",
                "NA",
                "Dirty",
                "New"
            };
        }

        [ObservableProperty]
        private List<string> _conditions;
    }
}

方式二:普通只读属性

using CommunityToolkit.Mvvm.ComponentModel;
using System.Collections.Generic;

namespace PlumbingCompany.Data
{
    public partial class Page7ViewModel : ObservableObject
    {
        public List<string> Conditions { get; }

        public Page7ViewModel()
        {
            Conditions = new List<string>
            {
                "Yes",
                "NA",
                "Dirty",
                "New"
            };
        }
    }
}

2. 修正XAML代码

  • 将Picker的ItemsSource绑定改为属性名Conditions
  • 确保Picker标签正确闭合(原代码未闭合标签)
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="PlumbingCompany.Views.Page7_RepairReport_1_"
             xmlns:viewModels="clr-namespace:PlumbingCompany.Data"
             Title="7. Repair Report (1)">

    <StackLayout Margin="20,10,20,10">
        <Label Text="Condition Found*" Margin="0,10,0,10"/>
        <Picker ItemsSource="{Binding Conditions}" /> 
    </StackLayout>

</ContentPage>

额外提示

如果后续需要动态更新列表内容,建议用ObservableCollection<string>替换List<string>,这样列表内容变化时Picker会自动刷新选项。

内容的提问来源于stack exchange,提问作者Александр Чайковский

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 21:47:21