nix86
nix86

Reputation: 3037

Button with Image Xamarin.Forms

I'm developing a cross pltform app with Xamarin.Forms. I want to make a button with an image but I dont know how to specify the path of the imge. When I use this annotation it works:

<Button Text="Naviga tra i Piani del Museo" Image="foo.png"/>

but when my image is inside some folders (folder1/folder2) the following code doesn't work:

<Button Text="Naviga tra i Piani del Museo" Image="folder1/folder2/foo.png"/>

So how can I correctly specify the path of my image?

Upvotes: 4

Views: 12603

Answers (4)

ColdMorningLight
ColdMorningLight

Reputation: 16

For using folders for Xamarin.Forms project this is what worked for me.

You need to put your resources (image file in this case), to folder inside Xamarin.Form project (for this example folder is called "Assets") and set Build Action "Content".

Secondly for resources to work with Android you need to put files to Resources>drawable folder inside Android project (here you cannot use any folders), Set Build Action "AndroidResource".

<ContentPage.Resources>
    <ResourceDictionary>
        <OnPlatform x:Key="StartButtonImage" 
                    x:TypeArguments="FileImageSource"
                    Android="button_image.png"
                    WinPhone="Assets\button_image.png"
                    iOS="Assets/button_image.png"/>
    </ResourceDictionary>
</ContentPage.Resources>


<ContentPage.Content>
    <Grid>
        <Button Image="{StaticResource StartButtonImage}" BackgroundColor="Transparent"/>
    </Grid>
</ContentPage.Content>

Pay attention that for iOs you need to make path using "/" and for WinPhone/UWP using "\".

Upvotes: 0

Kokul Jose
Kokul Jose

Reputation: 1732

Keeping the image common using PCL is a difficult task. So do it separately.

Keep in mind that you have to copy the images to Resources>drawable in case of android project.

Upvotes: 0

Ajay Sharma
Ajay Sharma

Reputation: 2881

You should specify Image property of button in OnPlatform tag to give different path for each platform. This is the example of Box View, you can try the same for Button Image property.

<BoxView HorizontalOptions="Center">
      <BoxView.Color>
        <OnPlatform x:TypeArguments="Color" 
          iOS="Green" 
          Android="#738182" 
          WinPhone="Accent" />
      </BoxView.Color>
      <BoxView.WidthRequest>
        <OnPlatform x:TypeArguments="x:Double" 
          iOS="30" 
          Android="40" 
          WinPhone="50" />
      </BoxView.WidthRequest>
 </BoxView>

Upvotes: -1

Jason
Jason

Reputation: 89082

You can't nest the images in folders. iOS and Android expect them to be resources, and WP expects them to be in the App's root folder.

The Xamarin Forms docs has a section on working with images.

Upvotes: 4

Related Questions