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

2023-02-13,,,,

接着上一篇"如何为面向 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);
}
}

运行效果

项目源码

Github | Gitee

知识共享许可协议

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

AlexChow

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

MAUI Blazor (Windows) App 动态设置窗口标题的相关教程结束。

《MAUI Blazor (Windows) App 动态设置窗口标题.doc》

下载本文的Word格式文档,以方便收藏与打印。