【问题标题】:How to reference image source files that are packaged with my metro style app?如何引用与我的 Metro 风格应用程序一起打包的图像源文件?
【发布时间】:2012-08-05 08:13:48
【问题描述】:

我有一个 .png 文件作为我的应用程序的内容。当我像这样在 xaml 中绑定它时

<ImageBrush x:Key="BtnBackImageBrush" ImageSource="/Assets/Images/back.png" />

一切正常。

我阅读了this article,当我尝试以编程方式访问此 .png 时出现错误。

我使用的代码:

Uri baseUri = new Uri("ms:appx");
Image img = new Image();
img.Source = new BitmapImage(new Uri(baseUri, "/Assets/Images/back.png"));
img.ImageFailed += (sender, args) => new MessageDialog("Error").ShowAsync();

我的问题是如何引用与我的 Metro 风格应用打包的图像源文件?

感谢您的建议。

更新: 我找到了答案! 我们需要使用父 FrameworkElement 设置 baseUri 而不是手动设置。例如:

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

感谢article

【问题讨论】:

    标签: c# windows-8 microsoft-metro


    【解决方案1】:

    新的 Uri("ms:appx");

    我认为这是最初问题的根源。该方案是 ms-appx 而不是 ms:appx

    错误的 URI:ms:appx://Assets/Images/back.png
    好的 URI:ms-appx://Assets/Images/back.png

    但是使用 FrameworkElement 并不是一个坏主意,如果您真的想确定其父级的范围 - 即使两者都有效,后者可能对读者来说可能更清楚您的意图(假设这是您的意图)。

    【讨论】:

    • 应该是ms-appx:///注意3/
    【解决方案2】:

    是的,你是对的,这就是你问题的答案。

    img.Source = ImageFromRelativePath(this, "Assets/Images/back.png");
    
    public static BitmapImage ImageFromRelativePath(FrameworkElement parent, string path)
    {
        var uri = new Uri(parent.BaseUri, path);
        BitmapImage bmp = new BitmapImage();
        bmp.UriSource = uri;
        return bmp;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-19
      • 1970-01-01
      相关资源
      最近更新 更多