Malcolm
Malcolm

Reputation: 1807

Set an image source from code behind

I have a textbox where user will enter the url of the image :

suppose the user enters the following string -> C:\Users\malcolm\Desktop\img.png

imgSilverPart is a image control AND imageUrl is a string what i am getting from a textbox.

imgSilverPart.Source = new BitmapImage(new Uri(imageUrl, UriKind.RelativeOrAbsolute));

But the image is not being displayed.

Upvotes: 2

Views: 3205

Answers (2)

Rene Schulte
Rene Schulte

Reputation: 2962

This won't work. Silverlight runs in a safe Sandbox and you can't just access a file on the desktop. So you have to call an OpenFileDialog, get the Stream to the file the user selected and set the Stream as source of the BitmapImage.

Add a Button in XAML and do the following in the Click event handler:

   private void Button_Click(object sender, RoutedEventArgs e)
   {
      OpenFileDialog openFileDlg = new OpenFileDialog();
      if (openFileDlg.ShowDialog().Value)
      {
         using (var stream = openFileDlg.File.OpenRead())
         {
            var bitmapImage = new BitmapImage();
            bitmapImage.SetSource(stream);
            imgSilverPart.Source = bitmapImage;
         }
      }
   }

As an alternative it's possible to use some special folders if your application runs in elevated trust mode as Out-Of-Browser app.

Upvotes: 4

PanJanek
PanJanek

Reputation: 6685

Maybe the kind of Uri was not determined corectly. Try tu use UriKind.Relative or UriKind.Absolute with valid relative or absolute url string.

Upvotes: 0

Related Questions