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

.NET MAUI页面启动时如何正确加载数据?

在.NET MAUI页面启动时加载数据的几种实用方式

1. 重写页面的OnAppearing生命周期方法

这是最常用的方式,页面每次显示时都会触发OnAppearing,如果只需要首次加载,可以加个标记避免重复调用。

public partial class HomePage : ContentPage
{
    private bool _hasLoaded = false;
    private readonly HomeViewModel _viewModel;

    public HomePage(HomeViewModel viewModel)
    {
        InitializeComponent();
        _viewModel = viewModel;
        BindingContext = _viewModel;
    }

    protected override async void OnAppearing()
    {
        base.OnAppearing();
        if (!_hasLoaded)
        {
            await _viewModel.LoadDataAsync();
            _hasLoaded = true;
        }
    }
}

注意:如果你的页面被导航回来后需要重新加载数据,去掉_hasLoaded的判断即可。

2. 在ViewModel构造函数中触发加载

如果用MVVM模式,直接在ViewModel初始化时发起数据请求。不过构造函数不能标记为async,所以用_ =来调用异步方法,同时记得处理异常。

public class HomeViewModel : INotifyPropertyChanged
{
    public ObservableCollection<Article> Articles { get; set; } = new();
    private readonly IArticleService _articleService;

    public HomeViewModel(IArticleService articleService)
    {
        _articleService = articleService;
        // 发起异步加载,忽略返回的Task避免编译器警告
        _ = LoadArticlesAsync();
    }

    private async Task LoadArticlesAsync()
    {
        try
        {
            var articles = await _articleService.GetLatestArticlesAsync();
            foreach (var article in articles)
            {
                Articles.Add(article);
            }
        }
        catch (Exception ex)
        {
            // 这里处理加载失败的情况,比如提示用户
            Debug.WriteLine($"加载数据失败: {ex.Message}");
        }
    }

    // INotifyPropertyChanged 实现代码省略
}

3. 绑定页面的Loaded事件

页面渲染完成后会触发Loaded事件,适合需要等页面元素都准备好后再加载数据的场景。

先在XAML中绑定事件:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MauiApp.HomePage"
             Loaded="HomePage_Loaded">
    <!-- 页面布局内容 -->
</ContentPage>

然后在后台代码中实现事件处理:

private async void HomePage_Loaded(object sender, EventArgs e)
{
    var viewModel = (HomeViewModel)BindingContext;
    await viewModel.LoadDataAsync();
    // 如果只需要加载一次,可以解绑事件
    ((ContentPage)sender).Loaded -= HomePage_Loaded;
}

4. 用AsyncCommand在页面初始化时执行

如果想更贴合MVVM的命令模式,可以定义一个异步命令,在页面构造函数中执行它。

ViewModel中定义命令:

public IAsyncCommand LoadDataCommand { get; }

public HomeViewModel(IArticleService articleService)
{
    _articleService = articleService;
    LoadDataCommand = new AsyncCommand(LoadArticlesAsync);
}

页面构造函数中调用:

public HomePage(HomeViewModel viewModel)
{
    InitializeComponent();
    BindingContext = viewModel;
    // 执行加载命令
    _ = viewModel.LoadDataCommand.ExecuteAsync(null);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 12:02:26