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

.NET 8 MAUI:Windows与macCatalyst下ToolbarItem悬停颜色修改

修改.NET 8 MAUI中Windows和macCatalyst平台ToolbarItem的悬停颜色

针对Windows和macCatalyst平台,需要通过平台特定的方式自定义ToolbarItem的悬停状态颜色,以下是具体实现:

Windows平台

Windows上MAUI的ToolbarItem基于WinUI的AppBarButton,可以直接覆盖系统默认的资源刷来修改悬停状态的前景/背景色,无需修改控件模板:

  1. 打开Platforms/Windows/App.xaml
  2. 在Application.Resources节点下添加以下资源,替换为你需要的颜色:
<Application.Resources>
    <!-- 修改悬停时的前景色 -->
    <SolidColorBrush x:Key="AppBarButtonPointerOverForegroundBrush" Color="White"/>
    <!-- 修改悬停时的背景色 -->
    <SolidColorBrush x:Key="AppBarButtonPointerOverBackgroundBrush" Color="#20FFFFFF"/>
</Application.Resources>

如果需要更精细的自定义(比如不同圆角、动画),可以复制AppBarButton的默认控件模板,修改PointerOver视觉状态的颜色属性。

macCatalyst平台

macCatalyst的ToolbarItem对应UIKit的UIBarButtonItem,需要通过Handler修改高亮(悬停)状态的颜色:

全局生效方式(所有ToolbarItem)

打开Platforms/MacCatalyst/Program.cs,在builder.UseMauiApp<App>()之后添加以下代码:

#if MACCATALYST
Microsoft.Maui.Handlers.ToolbarItemHandler.Mapper.AppendToMapping("CustomHoverColor", (handler, view) =>
{
    if (handler.PlatformView is UIBarButtonItem barButtonItem)
    {
        // 设置文字悬停颜色
        barButtonItem.SetTitleTextAttributes(new UIStringAttributes
        {
            ForegroundColor = UIColor.White // 替换为目标颜色
        }, UIControlState.Highlighted);

        // 设置图标悬停颜色(如果使用FontImageSource或图标)
        if (barButtonItem.Image != null)
        {
            barButtonItem.Image = barButtonItem.Image.ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate);
            barButtonItem.SetTintColor(UIColor.White, UIControlState.Highlighted);
        }
    }
});
#endif

页面局部生效方式(仅当前页面的ToolbarItem)

在页面的代码后台添加以下重写方法:

protected override void OnHandlerChanged()
{
    base.OnHandlerChanged();
#if MACCATALYST
    if (Handler is Microsoft.Maui.Handlers.PageHandler pageHandler)
    {
        foreach (var toolbarItem in ToolbarItems)
        {
            if (toolbarItem.Handler is Microsoft.Maui.Handlers.ToolbarItemHandler itemHandler && itemHandler.PlatformView is UIBarButtonItem barItem)
            {
                barItem.SetTitleTextAttributes(new UIStringAttributes { ForegroundColor = UIColor.White }, UIControlState.Highlighted);
                
                if (barItem.Image != null)
                {
                    barItem.Image = barItem.Image.ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate);
                    barItem.SetTintColor(UIColor.White, UIControlState.Highlighted);
                }
            }
        }
    }
#endif
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 02:50:21