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

求助:.NET MAUI中Picker选中卡片后数据未显示问题

问题:MAUI中Picker选中卡片后无法显示卡片数据

需求说明

通过API获取卡片数组,仅展示一张卡片;用户通过Picker选择卡片,选中后显示卡号、有效年月等信息。

当前问题

Picker已成功加载API返回的数据,但选中卡片后无任何数据展示。

已排查情况

代码无语法错误,Visual Studio未提示数据绑定错误,调试无异常,API正常返回数据。


问题分析与修复方案

1. 自定义OnPropertyChanged方法逻辑错误

当前代码重写的OnPropertyChanged逻辑存在缺陷,无法正确触发所有属性的变更通知,导致UI无法响应SelectedCard的变化。

修复代码:
替换原有的OnPropertyChanged实现,使用标准的INotifyPropertyChanged实现方式:

// 移除原自定义的OnPropertyChanged,替换为以下代码
public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

2. 未初始化默认选中卡片

GetCardsAsync获取数据后未设置SelectedCard初始值,导致IsCardSelected为false,绑定该属性的selectedCardLayout初始不可见,后续选中卡片时UI可能无法正确刷新。

修复代码:
在GetCardsAsync方法中添加默认选中逻辑:

private async Task GetCardsAsync()
{
    int id_client = App.ActiveAccount.id_client_account;
    string url = $"https://example";

    HttpClient client = new HttpClient();
    HttpResponseMessage response = await client.GetAsync(url);

    if (response.IsSuccessStatusCode)
    {
        string json = await response.Content.ReadAsStringAsync();
        CardsResponse responseObj = Newtonsoft.Json.JsonConvert.DeserializeObject<CardsResponse>(json);
        Cards = responseObj.data;
        // 设置默认选中第一张卡片
        if (Cards != null && Cards.Count > 0)
        {
            SelectedCard = Cards[0];
        }
    }
    else
    {
        Debug.WriteLine("Error: Unable to get Card data.");
    }
}

3. 显式指定Picker双向绑定(可选但推荐)

虽然MAUI中SelectedItem默认是双向绑定,但显式指定可避免潜在的绑定模式问题:

<Picker x:Name="CardPicker"
        ...
        SelectedItem="{Binding SelectedCard, Mode=TwoWay}"
        ... />

完整修复后的关键代码片段

// 替换原有的PropertyChanged事件和OnPropertyChanged方法
public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

GetCardsAsync方法修改

private async Task GetCardsAsync()
{
    int id_client = App.ActiveAccount.id_client_account;
    string url = $"https://example";

    HttpClient client = new HttpClient();
    HttpResponseMessage response = await client.GetAsync(url);

    if (response.IsSuccessStatusCode)
    {
        string json = await response.Content.ReadAsStringAsync();
        CardsResponse responseObj = Newtonsoft.Json.JsonConvert.DeserializeObject<CardsResponse>(json);
        Cards = responseObj.data;
        // 设置默认选中项
        if (Cards?.Count > 0)
        {
            SelectedCard = Cards[0];
        }
    }
    else
    {
        Debug.WriteLine("Error: Unable to get Card data.");
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 05:37:52