Change 'IconImageSource' of 'ToolbarItem'.

Abraham John 111 Reputation points
2021-04-13T00:47:30.233+00:00

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.

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,297 questions
{count} votes

Accepted answer
  1. JarvanZhang 23,951 Reputation points
    2021-04-13T02:15:37.093+00:00

    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.


0 additional answers

Sort by: Most helpful