我有一个 .png 文件作为我的应用程序的内容。当我像这样在 xaml 中绑定它时
<ImageBrush x:Key="BtnBackImageBrush" ImageSource="/Assets/Images/back.png" />
一切还好。
我阅读了这篇文章,当我尝试以编程方式访问此 .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;
}
感谢这篇文章。