Search code examples
c#wpfimagebindingembedded-resource

Binding image to property in wpf with image from resources


i have some pictures included to my project.

this line of code works fine:

<Image Stretch="UniformToFill" Source="/Images/OffsetSituations/offsetsituation1.jpg"

but i have to change the picture from the VM so i made a property to bind to:

private ImageSource _image;
public ImageSource Image
{
    get { return _image; }
    set
    {
        if (_image == value)
            return;
        _image = value;
        RaisePropertyChanged("Image");
    }
}

from another post here on stackoverflow i got this code and changed it a bit:

string picture = "offsetsituation1";
if (!string.IsNullOrEmpty(picture))
{
    var image = new BitmapImage(new Uri(String.Format("/Images/OffsetSituations/{0}.jpg", picture), UriKind.Relative));
    image.Freeze(); // -> to prevent error: "Must create DependencySource on same Thread as the DependencyObject"
    Image = image;
}
else
{
    Image = null;
}

now in the xaml:

<Image Stretch="UniformToFill" Source="{Binding Image}" Margin="5"/>

but there never is a picture.

i added MessageBox.Show(Image.ToString()); after Image = image; to debug. it shows /Images/OffsetSituations/offsetsituation1.jpg, so the path seems to be right.

what am i doing wrong here?


Solution

  • WPF provide implicit converters for most of the framework types including ImageSource

    all you have to do is provide the correct image path as string and let the implicit converter do the rest

    so change the type of Image property to string

    eg

    public string Image
    {
        get { return _image; }
        set
        {
            if (_image == value)
                return;
            _image = value;
            RaisePropertyChanged("Image");
        }
    }
    

    and assign the path as a string

    Image = String.Format("/Images/OffsetSituations/{0}.jpg", picture);
    

    that's all you need to show the image, rest will be handled by the framework

    implicit converter are so handy in many places including this one.