从后面的代码设置图像源

时间:2010-02-18 14:04:10

标签: silverlight

我有一个文本框,用户可以在其中输入图片的网址:

假设用户输入以下字符串 - > C:\ Users \用户马尔科姆\桌面\ img.png

imgSilverPart 是一个图片控件, imageUrl 是我从文本框中获取的字符串。

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

但图像未显示。

2 个答案:

答案 0 :(得分:4)

这不起作用。 Silverlight在安全的Sandbox中运行,您不能只访问桌面上的文件。 因此,您必须调用OpenFileDialog,将Stream获取到用户选择的文件,并将Stream设置为BitmapImage的源。

在XAML中添加一个Button,并在Click事件处理程序中执行以下操作:

   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;
         }
      }
   }

作为替代方案,如果您的应用程序在提升信任模式下作为Out-Of-Browser应用程序运行,则可以使用一些特殊文件夹。

答案 1 :(得分:0)

也许那种Uri没有被正确地确定。尝试使用UriKind.Relative或UriKind.Absolute与有效的相对或绝对url字符串。