2

MAUI Blazor (Windows) App 动态设置窗口标题 - AlexChow

 1 year ago
source link: https://www.cnblogs.com/densen2014/p/16950996.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

MAUI Blazor (Windows) App 动态设置窗口标题

原文链接 [https://www.cnblogs.com/densen2014/p/16950996.html]

接着上一篇"如何为面向 Windows 的 MAUI Blazor 应用程序设置窗口标题?"

Tips: 总所周知,MAUI 除了 Windows App 其他平台窗口是没有 Title 这回事的.

在 Blazor 里面可以直接给页面打上 <PageTitle>MauiApp7test</PageTitle> 动态设置页面标题,在 Windows 的 MAUI Blazor 应用程序设置是没有效果的,因为这个只是设置了 BlazorWebView 控件的标题,并不是真正的窗口标题, 接着上一篇的知识改造一下动态设置标题:

工程文件 Platforms -> Windows -> App.xaml.cs
using Microsoft.UI;
using Microsoft.UI.Windowing;
using Microsoft.UI.Xaml;
using WinRT.Interop;
...
namespace MauiApp7test.WinUI
{
    public partial class App : MauiWinUIApplication
    {
        public static object CurrentWindow;
        public static AppWindow AppWindow;

        protected override void OnLaunched(LaunchActivatedEventArgs args)
        {
            base.OnLaunched(args);

            CurrentWindow = Application.Windows[0].Handler?.PlatformView;
            IntPtr _windowHandle = WindowNative.GetWindowHandle(CurrentWindow);
            var windowId = Win32Interop.GetWindowIdFromWindow(_windowHandle);
            AppWindow = AppWindow.GetFromWindowId(windowId);
            
            SetTitle("MauiApp7test");
        }

        public static void SetTitle(string title) => AppWindow.Title = title;

        protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
    }
}

页面文件 Pages ->PagesIndex.razor

@code {
    protected override void OnAfterRender(bool firstRender)
    {
        if (firstRender)
        {
#if WINDOWS
            WinUI.App.SetTitle("MauiApp7test - Index");
#endif 
        }
    }
}

页面文件 FetchData.razor

@code {
    private WeatherForecast[] forecasts;

    protected override async Task OnInitializedAsync()
    {
#if WINDOWS
        WinUI.App.SetTitle("MauiApp7test - Fetchdata");
#endif
        forecasts = await ForecastService.GetForecastAsync(DateTime.Now);
    }
}
1980213-20221204220741085-2113201706.png
1980213-20221204220756228-635138729.png
1980213-20221204220807026-977189990.png

MAUI 还是一个新鲜事物,在官方还没支持的一些骚操作的情况下多发散思维,总能填坑的.

标题设置这里只是写了个方法去设置,也可以写成接口各平台实现,注入服务方式调用,理论上会更加通用一点.

Github | Gitee

知识共享许可协议

本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名AlexChow(包含链接: https://github.com/densen2014 ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请与我联系

AlexChow

今日头条 | 博客园 | 知乎 | Gitee | GitHub

image

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK