在 Metro 应用程序中从文件系统设置图像源



在ApplicationData.Current.RomanigFolder中,我保存了一个jpg文件。是否可以在流或内存流中读取此文件的内容并将其设置为图像源?

我在带有 .NET 4.0 的 WPF 应用程序中使用它,代码如下:(img 是一个 XAML 图像控件

BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.CacheOption = BitmapCacheOption.OnLoad;
StreamReader sr = new StreamReader(data.message.imageUrl);
bi.StreamSource = sr.BaseStream;
bi.EndInit();
img.Source = bi;
sr.Close();

对于Metro应用程序,我认为无法将StreamSource设置为BitmapImage。如何将图像文件设置为图像控件?

用于编写"Metro Style Apps"或为 Windows 8 构建的应用,以在 WPF 项目中设置图像的源。

代码如下:

// Usage
myImage.Source = ImageFromRelativePath(this, "relative_path_to_file_make_sure_build_set_to_content");
public static BitmapImage ImageFromRelativePath(FrameworkElement parent, string path)
{
    var uri = new Uri(parent.BaseUri, path);
    BitmapImage result = new BitmapImage();
    result.UriSource = uri;
    return result;
}

参考: http://www.codingbeta.com/programatically-setting-image-source-in-metro-style-apps-with-wpf/

最新更新