.NET MAUI选择器绑定与ViewModel文件

ldfqzlk8  于 2023-06-25  发布在  .NET
关注(0)|答案(1)|浏览(165)

我正在开发一个.net maui应用程序,并试图在应用程序的页面之一添加选择器。正如微软文档(“www.example.com”)中所写https://learn.microsoft.com/en-us/dotnet/maui/user-interface/controls/picker的,我可以直接在xaml文件中创建一个Item列表,但我需要在ViewModel类中声明这个列表,以便进行数据绑定。
下面是我的代码:XAML

<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 GetConditions}"> 
          </StackLayout>

XAML.cs

using PlumbingCompany.Data;

namespace PlumbingCompany.Views;

public partial class Page7_RepairReport_1_ : ContentPage
{
    public Page7_RepairReport_1_(Page7ViewModel viewModel)
    {
        BindingContext = viewModel;
        InitializeComponent();
    }
}

ViewModel.cs

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using PlumbingCompany.Models;
using PlumbingCompany.Views;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace PlumbingCompany.Data
{
    public partial class Page7ViewModel : ObservableObject
    {
        public Page7ViewModel()
        {

        }

        public List<string> GetConditions()
        {
            return new List<string>
            {
               "Yes",
               "NA",
               "Dirty",
               "New"
            };
        }
    }
}

它不会在选择器的菜单中显示任何项目。enter image description here
我尝试了不同的方法来声明列表,通过可观察的集合,数组,但都没有帮助。

oaxa6hgo

oaxa6hgo1#

由于您在项目中使用CommunityToolkit.Mvvm,因此需要将Picker的ItemsSource属性设置为Page7ViewModel中的IList集合,如下所示:

public partial class Page7ViewModel : ObservableObject 
{
        [ObservableProperty]
        public List<string> getConditions;

        public Page7ViewModel ()
        {
            GetConditions = new List<string>() {

                  "Yes",
                  "NA",
                  "Dirty",
                  "New"
            };
        }
}

相关问题