question

AbrahamJohn-8020 avatar image
0 Votes"
AbrahamJohn-8020 asked AbrahamJohn-8020 commented

Change 'IconImageSource' of 'ToolbarItem'.

Here I've a favourite icon in ToolbarItem. When user click the button it should toggle between two images "regular_heart.png" and "filled_heart.png" respectively.

In page.xaml:

 <ContentPage.ToolbarItems>
       <ToolbarItem x:Name="fav_Icon" IconImageSource="regular_heart.png" Clicked="FavItemClicked"/>
 </ContentPage.ToolbarItems>

In page.xaml.cs:

 private void FavItemClicked(object sender, EventArgs e)
 {
     if (fav_Icon.IconImageSource  == "regular_heart.png")
     {
         fav_Icon.IconImageSource = "filled_heart.png";
     }
     else
     {
         fav_Icon.IconImageSource = "regular_heart.png";
     }
 }

But this is getting error.

Help would be appreciated.

dotnet-xamarin
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

What is the error?

0 Votes 0 ·

Cannot compare ImageSource with string.

0 Votes 0 ·

1 Answer

JarvanZhang-MSFT avatar image
0 Votes"
JarvanZhang-MSFT answered JarvanZhang-MSFT commented

Hello,​

Welcome to our Microsoft Q&A platform!

The IconImageSource is type of ImageSource which is different with string. To detect the image source, please use IconImageSource.ToString() instead. Try the following code:

private void FavItemClicked(object sender, EventArgs e)
{
    if (fav_Icon.IconImageSource.ToString().Contains("regular_heart.png")))
    {
        fav_Icon.IconImageSource = "filled_heart.png";
    }
    else
    {
        fav_Icon.IconImageSource = "regular_heart.png";
    }
}

If there are only two cases, you could also use a bool property to detect the state.

bool testValue;
private void ToolbarItem_Clicked(object sender, EventArgs e)
{
    if (testValue)
    {
        fav_Icon.IconImageSource = "regular_heart.png";

        testValue = false;
    }
    else
    {
        fav_Icon.IconImageSource = "filled_heart.png";
        testValue = true;
    }
}


Best Regards,

Jarvan Zhang



If the response is helpful, please click "Accept Answer" and upvote it.

Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

The first code is not working. Think you forgot to add fav_Icon.IconImageSource:

 if (fav_Icon.IconImageSource. ToString().Contains("regular_heart.png"))

If you update this, I can mark it as answer.


0 Votes 0 ·

@AbrahamJohn-8020 Sorry for the mistake, I've updated the reply. Please check it.

0 Votes 0 ·