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

.NET MAUI中如何修改搜索栏搜索图标颜色(适配深色模式)

解决.NET MAUI搜索栏深色模式下搜索图标颜色无法修改的问题

方法1:使用MAUI Handler自定义(推荐)

MAUI的Handler是替代传统自定义渲染器的方案,针对不同平台单独处理搜索图标颜色:

配置全局Handler(在MauiProgram.cs中)

builder.ConfigureMauiHandlers(handlers =>
{
#if ANDROID
    handlers.AddHandler(typeof(SearchBar), typeof(CustomSearchBarHandler));
#elif IOS
    handlers.AddHandler(typeof(SearchBar), typeof(CustomSearchBarHandler));
#endif
});

Android平台自定义Handler

using Android.Widget;
using Microsoft.Maui.Platform;

public class CustomSearchBarHandler : SearchBarHandler
{
    protected override void ConnectHandler(MauiSearchBar platformView)
    {
        base.ConnectHandler(platformView);
        
        if (platformView is SearchView searchView)
        {
            int searchIconId = searchView.Context.Resources.GetIdentifier("android:id/search_mag_icon", null, null);
            if (searchIconId != 0)
            {
                var searchIcon = searchView.FindViewById<ImageView>(searchIconId);
                if (searchIcon != null)
                {
                    // 按需设置颜色,示例为深色模式下黑色
                    searchIcon.SetColorFilter(Android.Graphics.Color.ParseColor("#000000"));
                }
            }
        }
    }
}

iOS平台自定义Handler

using UIKit;
using Microsoft.Maui.Platform;

public class CustomSearchBarHandler : SearchBarHandler
{
    protected override void ConnectHandler(UISearchBar platformView)
    {
        base.ConnectHandler(platformView);
        
        platformView.SearchIconImage?.WithRenderingMode(UIImageRenderingMode.AlwaysTemplate);
        // 按需设置颜色,示例为深色模式下黑色
        platformView.TintColor = UIColor.Black;
    }
}

方法2:结合动态资源实现主题适配

如果需要随系统主题自动切换颜色,可通过资源字典配合Handler实现:

  1. 在Resources/Styles/Colors.xaml中添加动态颜色绑定:
<Color x:Key="SearchIconLight">#000000</Color>
<Color x:Key="SearchIconDark">#FFFFFF</Color>
<AppThemeBinding x:Key="SearchIconColor" Light="{StaticResource SearchIconLight}" Dark="{StaticResource SearchIconDark}" />
  1. 在Handler中引用动态资源(以Android为例):
var color = Application.Current.Resources["SearchIconColor"] as Color;
if (color != null)
{
    searchIcon.SetColorFilter(Android.Graphics.Color.Rgb(
        (int)(color.Red * 255),
        (int)(color.Green * 255),
        (int)(color.Blue * 255)
    ));
}

注意事项

  • Android不同版本的搜索图标ID可能存在差异,测试时需覆盖目标版本
  • iOS端必须将图标渲染模式设为AlwaysTemplate,才能修改tint颜色

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 19:38:25