Edward Tanguay
Edward Tanguay

Reputation: 193272

How do I bind an Image dynamically in XAML?

The following displays an image correctly in a silverlight usercontrol:

Image image = pagingManager.BaseApp.DatasourceManager.GetImage("helloWorld1");
ContentArea.Content = image;
...
<ContentControl x:Name="ContentArea"/>

However, I want to dynamically bind the image to XAML, e.g. like this:

#region ViewModelProperty: MainImage
private Image _mainImage;
public Image MainImage
{
    get
    {
        return _mainImage;
    }

    set
    {
        _mainImage = value;
        OnPropertyChanged("MainImage");
    }
}
#endregion
...
MainImage = pagingManager.BaseApp.DatasourceManager.GetImage("helloWorld1");

And my XAML is this but the result is that it shows nothing:

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

What do I need to put in my XAML to make it display the image object I have in my ViewModelProperty?

Upvotes: 2

Views: 6195

Answers (1)

Thomas Levesque
Thomas Levesque

Reputation: 292345

The Image.Source property is of type ImageSource, so your ViewModel should expose an ImageSource. Image is a control, it has nothing to do in the ViewModel.

If you do expose an Image control in your ViewModel (which is definitely a bad idea), then you should display it in a ContentControl, not an Image control :

<ContentControl Content="{Binding MainImage}" />

Upvotes: 5

Related Questions