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

如何在MAUI Windows应用的标题栏中添加刷新按钮

MAUI Windows 标题栏添加刷新按钮(菜单图标旁)实现方案

步骤1:配置标题栏允许自定义内容

在Shell的后台代码(如AppShell.xaml.cs)中,针对Windows平台开启标题栏自定义权限:

#if WINDOWS
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media;
using Windows.ApplicationModel.Core;
using Windows.UI.ViewManagement;
#endif

public partial class AppShell : Shell
{
    public AppShell()
    {
        InitializeComponent();
        InitializeWindowsTitleBar();
    }

#if WINDOWS
    private void InitializeWindowsTitleBar()
    {
        var coreTitleBar = CoreApplication.GetCurrentView().TitleBar;
        // 允许应用内容延伸到标题栏区域
        coreTitleBar.ExtendViewIntoTitleBar = true;

        var appWindow = Microsoft.UI.Xaml.Window.Current;
        var rootElement = appWindow.Content as FrameworkElement;
        if (rootElement == null) return;

步骤2:创建刷新按钮并匹配系统样式

在InitializeWindowsTitleBar方法内,生成刷新按钮并应用默认标题栏按钮样式,保证视觉统一:

// 创建刷新按钮
        var refreshButton = new Button();
        // 方案1:使用系统自带刷新图标
        refreshButton.Content = new SymbolIcon(Symbol.Refresh);
        // 应用标题栏按钮默认样式
        refreshButton.Style = (Style)appWindow.Resources["CaptionButtonStyle"];
        // 关联原有刷新逻辑
        refreshButton.Click += RefreshButton_Clicked;

如果要使用自定义图片替换系统图标,替换上述Content赋值代码:

// 方案2:使用自定义图片(需将图片添加到项目资源,路径按需调整)
        var refreshImage = new Image
        {
            Source = new BitmapImage(new Uri("ms-appx:///Resources/refresh.png")),
            Width = 16,
            Height = 16
        };
        refreshButton.Content = refreshImage;

步骤3:插入按钮到菜单图标旁

定位标题栏右侧的按钮容器,将刷新按钮插入到菜单图标(容器最后一个元素)前方:

// 找到标题栏右侧按钮容器
        var rightPanel = rootElement.FindName("TitleBarRightPanel") as StackPanel;
        if (rightPanel != null)
        {
            // 在菜单按钮前插入刷新按钮
            rightPanel.Children.Insert(rightPanel.Children.Count - 1, refreshButton);
        }
    }

    // 原有刷新逻辑事件
    private void RefreshButton_Clicked(object sender, RoutedEventArgs e)
    {
        // 此处编写你的刷新业务代码
    }
#endif
}

可选:适配系统主题颜色

添加主题颜色同步逻辑,让按钮颜色跟随系统浅色/深色模式变化:
在InitializeWindowsTitleBar方法末尾追加:

// 监听系统主题颜色变更
        var uiSettings = new UISettings();
        uiSettings.ColorValuesChanged += (s, e) => UpdateButtonColors(refreshButton);
        // 初始化按钮颜色
        UpdateButtonColors(refreshButton);
    }

    private void UpdateButtonColors(Button button)
    {
        var titleBar = ApplicationView.GetForCurrentView().TitleBar;
        button.Foreground = new SolidColorBrush(titleBar.ButtonForegroundColor);
    }

清理原有代码

移除Shell.TitleView中的刷新按钮,保留标题控件即可:

<Shell.TitleView>
    <Grid RowDefinitions="*" ColumnDefinitions="*">
        <controls:MyTitleControl Grid.Column="0" Title="MyTitle"/>
    </Grid>
</Shell.TitleView>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 07:44:50