Matheus
Matheus

Reputation: 1

Xamarin.Forms Image Source binding to string (MVVM)

I am intending to bind the source for an image from a URL I am loading in my ViewModel

In the xaml file, it works just fine if I use:

<Image Source="https://example.com/image.jpg"/>

However, it won't work if I use

ViewModel

public string Image = {get; set;}    
Image = "https://example.com/image.jpg";

XAML - I am setting the BindingContext to the ViewModel

<Image Source="{Binding Image}"/>

Any ideas?

Thanks

Upvotes: 0

Views: 1312

Answers (1)

Wendy Zang - MSFT
Wendy Zang - MSFT

Reputation: 10978

The code below should work. I set the binding in Xaml.

Xaml:

  <ContentPage.BindingContext>
    <local:ViewModel></local:ViewModel>
</ContentPage.BindingContext>
<ContentPage.Content>
    <StackLayout>
        <Image Source="{Binding Image}"></Image>
    </StackLayout>
</ContentPage.Content>

ViewModel:

 public class ViewModel
{
    public string Image { get; set; }
    public ViewModel()
    {
        Image = "https://aka.ms/campus.jpg"; //"https://example.com/image.jpg"
    }

}

Or you could set the binding in code behind:

Xaml:

 <ContentPage.Content>
    <StackLayout>
        <Image Source="{Binding Image}"></Image>
    </StackLayout>
</ContentPage.Content>

Code behind:

 public partial class Page2 : ContentPage
{
    public Page2()
    {
        InitializeComponent();
        this.BindingContext = new ViewModel();
    }
}
public class ViewModel
{
    public string Image { get; set; }
    public ViewModel()
    {
        Image = "https://aka.ms/campus.jpg"; //"https://example.com/image.jpg"
    }

}

Upvotes: 1

Related Questions