.NET MAUI MVVM Picker 绑定到列表

问题描述 投票:0回答:1

我必须遗漏一些愚蠢或明显的东西,但我无法为我的生活弄清楚这个。我的视图模型中有一个对象列表,我试图将其绑定到选择器并在选择器中显示对象的“名称”属性。

视图知道对象列表(作为可观察属性公开(社区工具包 mvvm)),但我无法访问要显示的对象内的任何属性,导致每个选择器显示中的空白条目列表中的对象。

public partial class SettingsPageViewModel : BaseViewModel
{
    [ObservableProperty]
    public Settings settingsObj;

    [ObservableProperty]
    public List<Language> langs;

    SettingsService settingsService;
    IConnectivity connectivity;

    public TextToSpeechSettingsPageViewModel(SettingsService settingsXMLServices, IConnectivity connectivitys)
    {
        this.settingsService = settingsXMLServices;
        this.connectivity = connectivitys;

        settingsObj = Task.Run(() => settingsService.GetSettingsAsync()).Result;

        Langs = settingsObj.Languages.Language;
    }
}

所以在上面,我用 settingsObj.Languages.Language 填充 Langs 可观察属性,它返回一个填充列表

在 XAML 视图中,我尝试按照我发现的各种示例的指示进行绑定(请注意,视图还有很多内容,但我只展示了相关部分:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:viewmodel="clr-namespace:MyAppName.ViewModel"
             x:DataType="viewmodel:SettingsPageViewModel"
             x:Class="MyAppName.Pages.SettingsPage"
             Title="Settings"
             x:Name="SettingsPage">
                    <StackLayout Grid.Column="0" Margin="10,0,10,0">
                        <Label Margin="0,0,0,0" FontAttributes="Bold" Text="Language:"/>
                        <Picker x:Name="LangSetting" SelectedIndexChanged="LangSetting_SelectedIndexChanged" ItemsSource="{Binding Langs, Mode=TwoWay}"
                                ItemDisplayBinding="{Binding Langs.Name}">
                        </Picker>
                    </StackLayout>

Intellisense 识别 Langs 并将给我 Capacity 或 Count,但不能访问类实例中的属性。就好像它看不到里面的实际对象,只是它是一个列表。如果我只是尝试使用 Name 而不是 Langs.Name,我会得到相同的结果。

如何让它向我显示与列表中的对象关联的属性?

c# mvvm binding maui picker
1个回答
0
投票

所以 Jason 在评论回复中的答案是

ItemDisplayBinding="{绑定名称}"

我曾假设它不会工作,因为在名称下有一个波浪线表示在数据上下文中找不到该成员,但这实际上并没有阻止它工作。

© www.soinside.com 2019 - 2024. All rights reserved.