如何在Xamarin Forms的ContentPage IconImageSource中显示标题栏图片
问题原因
你当前使用Shell作为应用的根容器,这种场景下ContentPage自带的IconImageSource属性默认仅用于Shell侧边菜单(Flyout)的选项图标,不会自动渲染到页面顶部的导航栏中,所以你写的配置才不生效。
解决方案
方案1:使用Shell.TitleView自定义导航栏(最灵活,推荐)
直接在你的AboutPage的XAML中添加Shell导航栏自定义内容,即可同时显示图标和标题,代码如下:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="HelloWorld.Views.AboutPage" Title="{Binding Title}"> <!-- 新增自定义导航栏内容 --> <Shell.TitleView> <StackLayout Orientation="Horizontal" Spacing="8" VerticalOptions="Center"> <Image Source="icon.png" WidthRequest="24" HeightRequest="24" /> <Label Text="{Binding Title}" FontSize="18" VerticalOptions="Center" /> </StackLayout> </Shell.TitleView> <ContentPage.ToolbarItems> <ToolbarItem IconImageSource="toolbar_icon.png"></ToolbarItem> </ContentPage.ToolbarItems> </ContentPage>
这个方案可以自由调整图标大小、间距、以及添加其他自定义控件,适配性最强。
方案2:切换为传统NavigationPage容器(不需要Shell功能时可用)
如果你的应用不需要Shell的Tab、侧边菜单等能力,可以直接修改App.xaml.cs的启动逻辑,用NavigationPage包裹根页面,原来写的IconImageSource="icon.png"配置就会直接生效:
// App.xaml.cs构造函数中修改 MainPage = new NavigationPage(new AboutPage());
核对项(可选)
如果配置完还是不显示,可以确认下icon.png的属性:
- 图片放在Android项目的
Resources/drawable目录下,生成操作设置为AndroidResource - 文件名全小写,不含空格、特殊字符,后缀名正确
内容的提问来源于stack exchange,提问作者Su Ming Yuan
相关产品推荐
相关产品推荐

