Can't show the icon for a button in Toolbar Items with UWP

I'm working on an app for the UWP and Android platforms. I want to set an icon for a button in the navigation toolbar. This is my code in XAML:

<ContentPage.ToolbarItems>
    <ToolbarItem x:Name="btnAbout" Text="ABOUT" Order="Primary" Clicked="OnNextPageButtonClicked"/>
</ContentPage.ToolbarItems>

and this is the code in the associated .cs file:

protected override void OnAppearing() 
{ 
    base.OnAppearing();
    btnAbout.IconImageSource = ImageSource.FromResource("Monk.about.ico"); 
}

Everything works just fine on Android, but in UWP, even though I can click the button, I can't see the icon.

Where did I go wrong?

Upvotes: 3

Views: 942

Answers (3)

I found the solution, I write it for those who need it:

it was necessary to define the path of the icons according to the type of OS destination for compilation.

For Android I had to copy the image to all the "drawable ..." folders and set its compilation property as "AndroidResource".

For UWP I had to copy the png file to the Assets folder and then set its compilation property as "Content".

Finally, you must indicate in the XAML file which paths to use depending on the type of compilation. The code is as follows:

<ContentPage.ToolbarItems>
        <ToolbarItem Text="ABOUT" Clicked="OnNextPageButtonClicked" Priority="0">
            <ToolbarItem.IconImageSource>
                <OnPlatform x:TypeArguments="FileImageSource">
                    <On Platform="Android">info</On>
                    <On Platform="UWP">Assets/info.png</On>
                </OnPlatform>
            </ToolbarItem.IconImageSource>
        </ToolbarItem> 
</ContentPage.ToolbarItems>

Upvotes: 2

Wendy Zang - MSFT
Wendy Zang - MSFT

Reputation: 10978

Do the change of the code below and set the .ico file Properties> Build Action to Content. enter image description here

Change:

btnAbout.IconImageSource = ImageSource.FromResource("Monk.about.ico");

To:

btnAbout.IconImageSource = ImageSource.FromFile("Monk.about.ico");

Or you could set the IconImageSource in XAML.

<ContentPage.ToolbarItems>
    <ToolbarItem Order="Primary"
                 Text="Icon Item"
                 Priority="0"
                 IconImageSource="Monk.about.ico"
                 Clicked="OnItemClicked" />

My .ico file:

enter image description here

My result:

enter image description here

Upvotes: 1

Martin Zikmund
Martin Zikmund

Reputation: 39102

I can confirm that while UWP can display an .ico file in a Image element, it does not work with the BitmapIcon, which Xamarin.Forms uses underneath for ToolbarItem. Therefore you will unfortunately not be able to use this very file on UWP. However, you can convert your icon to a .png image and that will display on all platforms without problems.

Upvotes: 1

Related Questions