【问题标题】:Bitmap images Binding位图图像绑定
【发布时间】:2013-12-15 22:26:03
【问题描述】:

这段代码有什么问题?当我在代码中将 XAML 中的图像源绑定到 firstimage 时,为什么 firstimage 没有显示在 XAML 页面上? 包含代码的类不是分部类。

if (ImagesAsSource[realty.ObjectId].Count == 0)
//private static Uri _baseUri = new Uri("ms-appx:///");
{
    Uri img = new Uri(_baseUri, "Assets/back.jpg");
    BitmapImage result = new BitmapImage();
    result.UriSource = img;
    // firstimage  is type of ImageSoure
    firstimage  =result;
}

//I tried this:

//private static Uri _baseUri = new Uri("ms-appx:///");
{
    Uri img = new Uri(_baseUri, "Assets/back.jpg");
    BitmapImage result = new BitmapImage(img );
    // firstimage  is type of ImageSoure
    firstimage  =result;
}

【问题讨论】:

  • 问题是你试图从 URI 字符串创建 BitmapImage。
  • 解决办法是什么?
  • 你可以试试答案中的代码
  • @Valin 从Uri(不是 URI 字符串)创建 BitmapImage 不是问题,而是创建 BitmapImage 的正确方法。
  • @user3105491 请显示您绑定到firstimage 的XAML。您确定firstimage 是公共财产吗?

标签: c# xaml windows-runtime


【解决方案1】:

这是正确的解决方案。

Uri _baseUri = new Uri("ms-appx:///");
Uri img = new Uri(_baseUri, "Assets/back.png");
BitmapImage result = new BitmapImage(img);
// firstimage  is type of ImageSoure
firstimage.Source = result;

【讨论】:

  • 包含的类不是部分类。
  • firstimage 似乎不是 Image 控件,而是 ImageSource 类型的字段或属性。
【解决方案2】:

你应该试试这样的:

Uri img = new Uri(_baseUri, "Assets/back.jpg");
var webClient = new WebClient();
byte[] imageBytes = webClient.DownloadData(img);
BitmapImage result = new BitmapImage(imageBytes);

其实我不知道你的 BitmapImage 的构造函数,所以可能你应该将 byte[] 转换为 Stream

【讨论】:

  • 这不是正确的解决方案,为什么要使用WebClient?如果应用不使用互联网怎么办?
  • 您使用了 URI,因此使用 webclient 从中获取数据似乎是合乎逻辑的。
  • 但它们是本地 URI,而不是 Internet URI。
  • 如果应用程序不使用互联网怎么办,OP 应该告诉用户有互联网来运行图像。这不是一个可行的解决方案 & BTW BitmapImage 不以 byte[] 作为参数。
  • -1 有两个原因。首先,将 WebClient 用于本地文件没有任何意义。其次,BitmapImage 没有将字节数组作为参数的构造函数。
猜你喜欢
  • 1970-01-01
  • 2013-01-29
  • 2011-08-19
  • 1970-01-01
  • 2014-09-29
  • 1970-01-01
  • 2015-09-25
  • 1970-01-01
  • 2017-11-11
相关资源
最近更新 更多