尝试在代码中创建图像,如下所示:
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"/>
使困惑。不知道为什么。如何在代码中获取动态图像?
更新:感谢克莱门斯提供的信息。试试下面的代码:
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.