【发布时间】:2025-12-12 12:35:02
【问题描述】:
尝试在 Xamarin 中加载 ToolbarItem 的图标时遇到问题:它不显示。工具栏当然存在。我已经处理了 Click 方法并且它可以工作,但是图标不可见。 “.ico”文件存在于 Android 项目的所有“drawable”文件夹中。这是我在另一个解决方案中使用的同一个 .ico 文件,在那里它作为 ToolbarItem 的图标工作得很好,但在这里它不起作用。我试图加载嵌入的图像,但它也不起作用。如果我设置它的 Text 属性,它会正确显示。我有一个主页,它是一个 MasterDetailPage,这个页面的详细信息是 RootPage。在 RootPage 我有 ToolbarItem。这是我的 xaml 代码和背后的代码:
主页:
<?xml version="1.0" encoding="utf-8" ?>
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:views="clr-namespace:ITEC.Views;assembly=ITEC"
x:Class="ITEC.Views.HomePage"
IsPresented="True">
<MasterDetailPage.Master>
<ContentPage Title="Home" Padding="0,20,0,0">
<StackLayout>
<ListView x:Name="listView">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding Title}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage>
</MasterDetailPage.Master>
<MasterDetailPage.Detail>
<views:RootPage/>
</MasterDetailPage.Detail>
</MasterDetailPage>
后面的代码:
using ITEC.Services;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace ITEC.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class HomePage : MasterDetailPage
{
private OptionService _optionService;
public HomePage()
{
InitializeComponent();
Detail=new NavigationPage(new RootPage());
_optionService = new OptionService();
listView.ItemsSource = _optionService.GetOptions();
}
}
}
根页面:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:embedded="clr-namespace:ITEC.MarkupExtensions"
x:Class="ITEC.Views.RootPage">
<ContentPage.ToolbarItems>
<ToolbarItem Icon="settings.ico" Clicked="MenuItem_OnClicked"></ToolbarItem>
</ContentPage.ToolbarItems>
<StackLayout>
<Label>Hello world</Label>
</StackLayout>
</ContentPage>
后面的代码:
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace ITEC.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class RootPage : ContentPage
{
public RootPage()
{
InitializeComponent();
}
private void MenuItem_OnClicked(object sender, EventArgs e)
{
DisplayAlert("Hello", "OK", "No");
}
}
}
【问题讨论】:
-
我做了一个基本的演示,但没有重现你的问题。请检查
.ico的属性,看看它是否作为AndroidResource添加到您的项目中。如果问题仍然存在,您能否分享一个可以重现此问题的基本演示? -
@ElvisXia-MSFT 似乎这是真正的问题。将构建操作设置为 AndroidResource 就可以了。当我从另一个项目复制粘贴文件时,我不确定该文件是否具有正确的构建操作。但是有没有办法使用嵌入式资源中的图标?这样会更干净,而不是将一个文件移动到 6 个不同的可绘制文件夹
标签: c# xaml xamarin xamarin.android