azh*_*kov 7 c# microsoft-metro windows-8
我有一个.png文件作为我的应用程序的内容.当我像这样绑定它在xaml中时
<ImageBrush x:Key="BtnBackImageBrush" ImageSource="/Assets/Images/back.png" />
Run Code Online (Sandbox Code Playgroud)
一切还好.
我读了这篇文章,当我尝试以编程方式访问此.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();
Run Code Online (Sandbox Code Playgroud)
我的问题是如何引用我的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;
}
Run Code Online (Sandbox Code Playgroud)
谢谢你的这篇文章.
小智 9
新的Uri("ms:appx");
我认为这是原始问题的根源.该方案是ms-appx而不是ms:appx
错误的URI:ms:appx://Assets/Images/back.png
好的URI:ms-appx://Assets/Images/back.png
但是使用FrameworkElement并不是一个坏主意,如果你真的试图像它的父类那样做范围 - 即使两者都有效,后者可能会更清楚你的意图的读者(假设这是你的意图).
小智 6
是的你是对的,这是你问题的答案.
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19387 次 |
| 最近记录: |