.NET MAUI桌面开发:如何自定义应用栏(修改颜色及添加内容)
.NET MAUI桌面应用栏自定义:修改颜色+添加内容
用户当前的应用栏状态:

一、修改应用栏颜色
1. 跨平台基础设置
在App.xaml中通过样式统一设置所有NavigationPage的应用栏颜色:
<Application xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="YourAppName.App"> <Application.Resources> <Style TargetType="NavigationPage"> <!-- 设置应用栏背景色 --> <Setter Property="BarBackgroundColor" Value="#2C3E50" /> <!-- 设置应用栏文字颜色 --> <Setter Property="BarTextColor" Value="White" /> </Style> </Application.Resources> </Application>
2. Windows系统级标题栏定制
如果需要修改Windows窗口的系统标题栏(包括边框、非激活状态颜色),在Platforms/Windows/App.xaml.cs的OnLaunched方法中添加代码:
protected override void OnLaunched(LaunchActivatedEventArgs args) { base.OnLaunched(args); var appWindow = Microsoft.UI.Xaml.Window.Current.AppWindow; var titleBar = appWindow.TitleBar; // 激活时的背景色 titleBar.BackgroundColor = Windows.UI.Color.FromArgb(255, 44, 62, 80); // 激活时的文字颜色 titleBar.ForegroundColor = Windows.UI.Colors.White; // 非激活时的背景色 titleBar.InactiveBackgroundColor = Windows.UI.Color.FromArgb(255, 54, 72, 90); // 非激活时的文字颜色 titleBar.InactiveForegroundColor = Windows.UI.Colors.LightGray; }
二、为应用栏添加自定义内容
通过NavigationPage.TitleView可以在应用栏中添加任意UI元素,比如图标、按钮、标签等。
1. 页面中添加自定义内容
打开目标页面(如MainPage.xaml),在页面根节点内添加NavigationPage.TitleView:
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="YourAppName.MainPage"> <!-- 自定义应用栏内容 --> <NavigationPage.TitleView> <StackLayout Orientation="Horizontal" Spacing="10" Padding="10" HorizontalOptions="FillAndExpand"> <!-- 左侧图标 --> <Image Source="app_icon.png" HeightRequest="30" WidthRequest="30" /> <!-- 标题文本 --> <Label Text="我的MAUI应用" FontSize="18" TextColor="White" VerticalOptions="Center" /> <!-- 右侧按钮(对齐到右侧) --> <Button Text="设置" TextColor="White" BackgroundColor="Transparent" HorizontalOptions="EndAndExpand" Margin="0,0,10,0" /> </StackLayout> </NavigationPage.TitleView> <!-- 页面主体内容 --> <StackLayout> <!-- 这里放你的页面内容 --> </StackLayout> </ContentPage>
2. 必要配置
- 确保主页面被
NavigationPage包裹,在App.xaml.cs中设置:
public App() { InitializeComponent(); MainPage = new NavigationPage(new MainPage()); }
- 如果是Windows平台,想要让自定义内容覆盖系统标题栏区域,在
Platforms/Windows/App.xaml.cs的OnLaunched中添加:
// 让内容延伸到系统标题栏 appWindow.TitleBar.ExtendsContentIntoTitleBar = true; // 隐藏默认系统标题文字 appWindow.TitleBar.Title = string.Empty;
内容的提问来源于stack exchange,提问作者Excell
相关产品推荐
相关产品推荐

