代码简化了增加左侧的导航栏,跳转等。之后例子功能,都会基于此扩展。

using CommunityToolkit.Maui.Extensions;
using Microsoft.Maui.Controls;
using Microsoft.Maui.Controls.PlatformConfiguration.AndroidSpecific;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Shares
{
    public static class ShellExtensions
    {
        static ShellExtensions()
        {
            //Shell.Current.PropertyChanged += AppShellPropertyChanged;
            //Shell.Current.Navigating += AppShellNavigate;
        }
        public static object? Create(this Shell shell, string target, params object[] parameters)
        {
            var viewType = Type.GetType($"{target}, {target.Split(".")[0]}");
            if (viewType == null)
            {
                shell.MessageBox("错误", $"无法找到类型 {target},请确保它已正确命名空间并且已加载到应用程序中");
                return null;
            }
            return Activator.CreateInstance(viewType, args:parameters);
        }
        private static void RegisterRoute(this Shell shell, string target)
        {
            Type? type = Type.GetType($"{target}, {target.Split('.')[0]}");
            try
            {
                Routing.RegisterRoute(target, type);
            }
            catch (Exception ex)
            {
                shell.MessageBox("错误", $"无法注册路由到 {target},请确保类型存在并且已正确命名空间, 错误为{ex.Message}");
            }
        }
        public static void Navigate(this Shell shell, string target)
        {
            var parts = target.Split('.');
            ShellSection shellSection = new ShellSection { Title = string.Join(".", parts.Skip(1).Take(parts.Length - 1)) };     
            ShellContent content;
            try
            {
                content = new ShellContent()
                {
                    Content = shell.Create(target)
                };
            }
            catch (Exception ex)
            {
                shell.MessageBox("错误", $"无法创建类型 {target} 的实例,确保它是Page的子类, 错误为{ex.Message}");
                return;
            }
            shellSection.Items.Add(content);
            shell.Items.Add(shellSection);
        }
        public static void GoTo(this Shell shell, string target, bool back = false)
        {
            Task task = shell.GoToAsync(target, false);
            if (task.Status == TaskStatus.Faulted)
            {
                //自动注册路由
                shell.RegisterRoute(target);
                task = shell.GoToAsync(target, false);
                if (task.Status == TaskStatus.Faulted)
                {
                    shell.MessageBox("错误", $"无法导航到 {target},请确保它已正确注册路由或存在于应用程序中");
                    return;
                }
            }
            Shell.SetBackButtonBehavior(shell.CurrentPage, new BackButtonBehavior
            {
                IsVisible = back,
            });
        }
        public static void PushModal(this Shell shell, string target, string targetViewModel="", params object[] parameters)
        {
            Page? page = shell.Create(target) as Page;
            if (page == null)
            {
                shell.MessageBox("错误", $"无法创建类型 {target} 的实例,确保它是Page的子类");
                return;
            }
            if (!string.IsNullOrEmpty(targetViewModel))
            {
                page.BindingContext = shell.Create(targetViewModel, parameters);
            }
             shell.Navigation.PushModalAsync(page);
        }
        public static void PopModel(this Shell shell)
        {
            shell.Navigation.PopModalAsync();
        }
        public static void MessageBox(this Shell shell, string title, string message, string cancel = "OK")
        {
            shell.CurrentPage.DisplayAlert(title, message, cancel);
        }
        public static void Popup(this Shell shell, string target, bool stayOpen = false)
        {
            ContentView? view = shell.Create(target) as ContentView;
            if (view == null)
            {
                shell.MessageBox("错误", $"无法创建类型 {target} 的实例,确保它是View的子类");
                return;
            }
            shell.CurrentPage.ShowPopupAsync(view, new CommunityToolkit.Maui.PopupOptions
            {
                CanBeDismissedByTappingOutsideOfPopup = !stayOpen,
            });
        }
        public static void ClosePopup(this Shell shell)
        {
            shell.ClosePopupAsync();
        }
    }
}

这样之后只需要修改AppShell.xaml.cs,简单添加NavigationBar就完成导航栏的修改啦。

using Shares;
using System.Diagnostics;

namespace MauiViews
{
    public partial class AppShell : Shell
    {
        public AppShell()
        {
            InitializeComponent();
            //添加导航栏
            this.NavigateBar("MauiViews.MauiDemos.Demo1.View");
            this.NavigateBar("MauiViews.MauiDemos.Demo2.View");
            this.NavigateBar("MauiViews.MauiDemos.Demo3.View");
        }
    }
}

 

posted on 2025-06-09 11:29  dalgleish  阅读(52)  评论(0)    收藏  举报