Binding image to property in wpf with image from resources

别来无恙 提交于 2019-12-13 05:02:12

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/25913901/binding-image-to-property-in-wpf-with-image-from-resources

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!