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

.NET MAUI:MVVM模式下从数据库恢复Picker选中值的实现疑问

在.NET MAUI MVVM中恢复Picker选中值的正确实现

核心思路

完全遵循MVVM原则:ViewModel只处理数据逻辑,不直接操作UI控件;通过数据绑定实现Picker选中值的自动同步,替代直接操作SelectedIndex的方式。


步骤1:ViewModel添加选中项属性及匹配逻辑

在ViewModel中添加与Picker选中项对应的Observable属性,同时处理保存的字符串值与选项列表的匹配:

using CommunityToolkit.Mvvm.ComponentModel;
using System.Linq;

public partial class YourViewModel : ObservableObject
{
    // 选项列表(建议用ObservableCollection,确保列表变更时UI自动更新)
    [ObservableProperty]
    private ObservableCollection<GuaranteeModel> guaranteeOptionsList;

    // Picker选中的数据对象
    [ObservableProperty]
    private GuaranteeModel selectedGuarantee;

    // 从数据库加载的保存字符串值
    [ObservableProperty]
    private string savedGuaranteeValue;

    // 保存值变更时自动匹配选项列表中的对应对象
    partial void OnSavedGuaranteeValueChanged(string newValue)
    {
        if (GuaranteeOptionsList != null && !string.IsNullOrEmpty(newValue))
        {
            SelectedGuarantee = GuaranteeOptionsList.FirstOrDefault(g => g.Guarantee == newValue);
        }
    }

    // 选中项变更时,处理原SelectedIndexChanged中的逻辑(如控制其他元素可见性)
    partial void OnSelectedGuaranteeChanged(GuaranteeModel newValue)
    {
        // 替换原GuaranteePicker_SelectedIndexChanged中的代码
        // 示例:IsOtherControlVisible = newValue != null && newValue.SomeProperty == "目标值";
    }

    [RelayCommand]
    async Task Appearing()
    {
        try
        {
            DataModel = new Model.Core.JobEntryModel();
            await DataModel.Load(this.PageParameters);
            
            // 1. 先加载选项列表
            var dbGuarantees = await db.Table<GuaranteeModel>()
                .Where(x => x.ResCom == Constants.kGuaranteeTypeNew)
                .ToListAsync();
            GuaranteeOptionsList = new ObservableCollection<GuaranteeModel>(dbGuarantees);
            
            // 2. 设置保存的字符串值,触发自动匹配选中项
            SavedGuaranteeValue = DataModel.SavedGuaranteeString; // 假设DataModel存储了该字符串
        }
        catch (Exception ex)
        {
            // 异常处理逻辑
        }
    }
}

步骤2:修改Picker的XAML绑定

移除x:Name和SelectedIndexChanged事件,改为绑定SelectedItem到ViewModel的SelectedGuarantee属性:

<Picker                                   
    ItemsSource="{Binding GuaranteeOptionsList}"
    ItemDisplayBinding="{Binding Guarantee}"
    SelectedItem="{Binding SelectedGuarantee, Mode=TwoWay}">
</Picker>

关键说明

  1. 摒弃直接操作SelectedIndex:MVVM模式下,ViewModel不应依赖UI控件的索引值,绑定SelectedItem直接操作数据对象,更符合模式设计要求。
  2. 自动同步UI:由于GuaranteeOptionsList和SelectedGuarantee都是ObservableProperty,数据加载完成后,属性变更会自动通知UI刷新Picker选中状态,无需关心OnAppearing和AppearingCommand的执行顺序。
  3. 迁移事件逻辑:通过ViewModel中自动生成的OnSelectedGuaranteeChanged部分方法,实现原SelectedIndexChanged中的业务逻辑,完全脱离对UI控件的依赖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 20:47:14