Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: "Value of type 'String' cannot be converted to 'System.Windows.Media.ImageSource'."

I'm trying to set a WPF Image's source.

XAML works:

<Image Name="ImageThing"
       Source="images/Thing.png"/>

Visual Basic fails:

ImageThing.Source = "images/Thing.png"

…with this exception:

Value of type 'String' cannot be converted to 'System.Windows.Media.ImageSource'.

How do I create the System.Windows.Media.ImageSource that I need?


Update

This code adapted from an MSDN example works:

Dim bmp As New BitmapImage()
bmp.BeginInit()
bmp.UriSource = New Uri("images/Thing.png", UriKind.Relative)
bmp.EndInit()
ImageThing.Source = bmp
like image 910
Zack Peterson Avatar asked Mar 31 '09 19:03

Zack Peterson


4 Answers

WPF uses an implicit type converter to convert the xaml string to the expected type. In code you are statically bound by the object type... If you look at the example here it shows how to set the source property to a BitmapImage that is generated from a local uri programatically.

like image 189
Quintin Robinson Avatar answered Nov 10 '22 16:11

Quintin Robinson


you will probably need to do something like this

Uri i = new Uri("images\\Thing.png");

keep in mind that you need to use a \ not a / for a windows file system

Take a look here

like image 21
CodeMonkey1313 Avatar answered Nov 10 '22 14:11

CodeMonkey1313


It can be even easier than the above:

ImageThing.Source = New BitmapImage(New Uri("images/Thing.png", UriKind.Relative))

like image 36
cjbarth Avatar answered Nov 10 '22 15:11

cjbarth


Just change xaml file like this.

<Image Name="ImageThing">
    <Image.Source>
       <BitmapImage UriSource="images/Thing.png" />
    </Image.Source>
</Image>
like image 29
Daniex Avatar answered Nov 10 '22 14:11

Daniex