尝试在代码中创建图像,如下所示:
sp = new StackPanel() { Orientation = Orientation.Horizontal };
Image myImage = new Image() { HorizontalAlignment = HorizontalAlignment.Left, Width = 16, Height = 16, Margin = new Thickness(1, 0, 0, 0) };
MyImage.Source = new BitmapImage(new Uri("/MyAssembly;component/folder/image1.png", UriKind.RelativeOrAbsolute));
sp.Children.Add(MyImage);
然后运行应用程序,图像不显示。用Fiddler检查数据并得到404错误。上图的来源如下:
http://localhost:80/MyAssembly;component/folder/image1.png
但是这个图像被编译到一个程序集MyAssembly中。
可以使用以下标记从程序集中获取图像xaml:
<Image Source="/MyAssembly;component/folder/image1.png"/>
混淆。不知道为什么。如何在代码中获取动态图像?
更新:感谢Clemens提供的信息。请尝试以下代码:
sp = new StackPanel() { Orientation = Orientation.Horizontal };
ImageSourceConverter converter = new ImageSourceConverter();
Image myImage = new Image() { HorizontalAlignment = HorizontalAlignment.Left, Width = 16, Height = 16, Margin = new Thickness(1, 0, 0, 0) };
MyImage.Source = (ImageSource)converter.ConvertFromString("/MyAssembly;component/folder/image1.png");
sp.Children.Add(MyImage);
结果与以前相同。来自Fiddler的消息: 您要查找的资源已被删除,名称已更改或暂时不可用。
此资源仍为
http://localhost:80/MyAssembly;component/folder/image1.png.
答案 0 :(得分:0)
不知道在Silverlight中为Uri使用什么方案,你可以在WPF中编写类似pack://application,,,/MyAssembly;component/folder/image1.png
的内容。
但幸运的是你总能写下这个:
ImageSourceConverter converter = new ImageSourceConverter();
MyImage.Source = (ImageSource)converter.ConvertFromString(
"/MyAssembly;component/folder/image1.png");
当然也可以显式设置相对URI:
MyImage.Source = new BitmapImage(
new Uri("/MyAssembly;component/folder/image1.png", UriKind.Relative));
但请注意,image1.png
的{{3}}在任何情况下都必须设置为Resource
。