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

.NET MAUI应用启动时如何判定并展示对应内容页面?

.NET MAUI 启动时数据库检查与页面跳转实现步骤

1. 编写数据库工具类,实现路径与文件检查

先创建一个静态工具类,用来管理数据库的存储路径和文件检查逻辑,避免代码重复:

using System.IO;
using System.Collections.Generic;
using System.Linq;

public static class DbHelper
{
    // 获取应用私有数据库目录(避免权限问题)
    public static string GetDbDirectory()
    {
        return Path.Combine(FileSystem.AppDataDirectory, "Databases");
    }

    // 获取目录下所有数据库文件(示例用.db后缀,可自行修改)
    public static List<string> GetExistingDatabases()
    {
        var dbDir = GetDbDirectory();
        // 目录不存在则创建,避免后续报错
        if (!Directory.Exists(dbDir))
        {
            Directory.CreateDirectory(dbDir);
            return new List<string>();
        }
        // 提取文件名(不含路径)返回
        var dbFiles = Directory.GetFiles(dbDir, "*.db")
                               .Select(Path.GetFileName)
                               .ToList();
        return dbFiles;
    }
}

2. 在App启动时添加判断逻辑

替换App.xaml.cs中的OnStart方法,实现启动时的数据库检查与页面跳转:

protected override async void OnStart()
{
    base.OnStart();

    var dbList = DbHelper.GetExistingDatabases();
    
    if (dbList.Count > 0)
    {
        // 弹出系统自带的选择弹窗
        var selectedDb = await Application.Current.MainPage.DisplayActionSheet(
            "选择要使用的数据库", 
            "取消", 
            null, 
            dbList.ToArray()
        );
        
        if (!string.IsNullOrEmpty(selectedDb) && selectedDb != "取消")
        {
            // 跳转到主页面,传递选中的数据库名称(转义避免特殊字符问题)
            await Shell.Current.GoToAsync($"//MainPage?dbName={Uri.EscapeDataString(selectedDb)}");
        }
        else
        {
            // 用户取消选择,跳转到新建数据库页面
            await Shell.Current.GoToAsync("//CreateDbPage");
        }
    }
    else
    {
        // 无数据库文件,直接跳转到新建页面
        await Shell.Current.GoToAsync("//CreateDbPage");
    }
}

注意:OnStart仅在应用首次启动时触发,如果需要每次应用从后台恢复也检查,可把逻辑移到OnResume方法中

3. 配置AppShell路由

在AppShell.xaml中注册需要跳转的页面路由,让Shell能识别页面路径:

<Shell xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
       xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
       xmlns:local="clr-namespace:你的应用命名空间"
       x:Class="你的应用命名空间.AppShell">

    <!-- 注册新建数据库页面路由 -->
    <ShellContent Route="CreateDbPage" ContentTemplate="{DataTemplate local:CreateDbPage}" />
    <!-- 注册主页面路由 -->
    <ShellContent Route="MainPage" ContentTemplate="{DataTemplate local:MainPage}" />

</Shell>

4. 实现新建数据库页面(结合基础MVVM)

第一步:安装MVVM工具包

先安装CommunityToolkit.Mvvm NuGet包,简化MVVM的绑定实现。

第二步:新建页面与ViewModel

CreateDbPage.xaml(页面布局)

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:viewmodel="clr-namespace:你的应用命名空间.ViewModels"
             x:Class="你的应用命名空间.CreateDbPage"
             Title="新建数据库">

    <!-- 设置页面的ViewModel -->
    <ContentPage.BindingContext>
        <viewmodel:CreateDbPageViewModel />
    </ContentPage.BindingContext>

    <VerticalStackLayout Padding="20" Spacing="15">
        <!-- 绑定数据库名称输入框 -->
        <Entry Placeholder="输入数据库名称" Text="{Binding DbName}" />
        <!-- 绑定创建按钮的命令 -->
        <Button Text="创建并使用" Command="{Binding CreateDbCommand}" />
    </VerticalStackLayout>
</ContentPage>

CreateDbPageViewModel.cs(业务逻辑)

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.IO;

// 继承ObservableObject实现属性通知
public partial class CreateDbPageViewModel : ObservableObject
{
    // 自动生成DbName属性的get/set,以及属性变更通知
    [ObservableProperty]
    private string _dbName;

    // 自动生成CreateDbCommand命令
    [RelayCommand]
    private async Task CreateDb()
    {
        if (string.IsNullOrWhiteSpace(DbName))
        {
            await Application.Current.MainPage.DisplayAlert("提示", "请输入数据库名称", "确定");
            return;
        }

        var dbDir = DbHelper.GetDbDirectory();
        var dbPath = Path.Combine(dbDir, $"{DbName}.db");
        
        // 这里添加创建数据库的逻辑(比如用SQLite创建空库)
        // 示例:
        // var conn = new SQLite.SQLiteConnection(dbPath);
        // conn.CreateTable<你的实体类>();
        // conn.Close();

        // 创建完成后跳转到主页面,传递数据库名称
        await Shell.Current.GoToAsync($"//MainPage?dbName={Uri.EscapeDataString(DbName)}");
    }
}

5. 主页面接收数据库参数

如果主页面需要根据选中的数据库名称初始化连接,可以在主页面的ViewModel中通过QueryProperty接收参数:

using CommunityToolkit.Mvvm.ComponentModel;

[QueryProperty(nameof(DbName), "dbName")]
public partial class MainPageViewModel : ObservableObject
{
    [ObservableProperty]
    private string _dbName;

    // 页面加载时可使用DbName初始化数据库
    public void OnAppearing()
    {
        if (!string.IsNullOrEmpty(DbName))
        {
            // 初始化数据库连接逻辑
        }
    }
}

然后在MainPage的OnAppearing方法中调用ViewModel的OnAppearing:

protected override void OnAppearing()
{
    base.OnAppearing();
    ((MainPageViewModel)BindingContext).OnAppearing();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 10:25:42