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

.NET Maui代码绑定ItemsSource后,ListView无法刷新问题求助

解决方案

问题出在你直接把ListView的ItemsSource赋值为_vm.Questions的当前值,而非使用数据绑定。当后续ViewModel中Questions属性更新时,ListView无法感知到变化,因为它只持有初始的null引用。

步骤1:改用数据绑定替代直接赋值

修改View的代码,使用SetBinding建立ListView和ViewModel属性的绑定关系,这样当ViewModel的Questions属性变化时,ListView会自动更新:

public SurveyQuestionsView(SurveyQuestionsViewModel vm)
{
    _vm = vm;
    BindingContext = _vm;

    var listView = new ListView();
    // 替换直接赋值为数据绑定
    listView.SetBinding(ListView.ItemsSourceProperty, nameof(SurveyQuestionsViewModel.Questions));

    Content = listView;
}

步骤2:确保LoadData方法被执行

你需要确保LoadData方法被调用才能填充Questions数据。可以在ViewModel的构造函数中异步调用它(用_ =避免异步警告):

public partial class SurveyQuestionsViewModel : ObservableObject
{
    private readonly ISurveyApplication _surveyApplication;
    private SurveyModel currentSurvey; // 假设该变量已正确初始化

    public SurveyQuestionsViewModel(ISurveyApplication surveyApplication)
    {
        _surveyApplication = surveyApplication;
        // 启动数据加载
        _ = LoadData();
    }
        
    [ObservableProperty]
    private ObservableCollection<SurveyQuestionModel> questions;
    
    async Task LoadData()
    {
        var data = await _surveyApplication.GetSurveyQuestionsBySurveyId(currentSurvey.SurveyId);
        Questions = new ObservableCollection<SurveyQuestionModel>(data);
    }
}

原理说明

  • 你的ViewModel继承了ObservableObject,且Questions属性用[ObservableProperty]标记,这会自动生成PropertyChanged事件通知。
  • 使用数据绑定后,ListView会监听Questions属性的PropertyChanged事件,当属性值更新时自动刷新数据源。
  • 直接赋值ItemsSource只会让ListView持有属性的当前引用,无法感知后续的属性值变化。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 14:22:21