Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically set the Source of an Image (XAML)

I am working on a Windows 8 app. I need to know how to programmatically set the Source of an Image. I assumed that the Silverlight approach would work. However, it doesn't. Does anybody know how to do this? The following will not work:

string pictureUrl = GetImageUrl(); Image image = new Image(); image.Source = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri(pictureUrl, UriKind.Relative)); image.Stretch = Stretch.None; image.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Left; image.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Center; 

I get an Exception that says: "The given System.Uri cannot be converted into a Windows.Foundation.Uri."

However, I can't seem to find the Windows.Foundation.Uri type.

like image 850
Villager Avatar asked Jun 29 '12 18:06

Villager


People also ask

How to set image source in wpf XAML?

Here's how to set the source to an image from the app package. Image img = new Image(); BitmapImage bitmapImage = new BitmapImage(); Uri uri = new Uri("ms-appx:///Assets/Logo.png"); bitmapImage. UriSource = uri; img. Source = bitmapImage; // OR Image img = new Image(); img.

How do I upload an image to UWP?

If you insert the image manually, then you need to Add->existing item. Then select the image, rigth click, properties and in Build Action, make sure "content" is the default.


2 Answers

I just tried

Image.Source = new BitmapImage(     new Uri("http://yourdomain.com/image.jpg", UriKind.Absolute)); 

And it works without problems... I'm using System.Uri here. Maybe you have a malformed URI or you have to use an absolute URI and use UriKind.Absolute instead?

like image 132
Rico Suter Avatar answered Sep 29 '22 20:09

Rico Suter


This is what I use:

string url = "ms-appx:///Assets/placeHolder.png"; image.Source = RandomAccessStreamReference.CreateFromUri(new Uri(url)); 
like image 21
avens19 Avatar answered Sep 29 '22 18:09

avens19