我正在尝试在代码中设置WPF图像的源代码.图像作为资源嵌入到项目中.通过查看示例,我提出了以下代码.由于某种原因,它不起作用 - 图像不显示.
通过调试,我可以看到流包含图像数据.那有什么不对?
Assembly asm = Assembly.GetExecutingAssembly();
Stream iconStream = asm.GetManifestResourceStream("SomeImage.png");
PngBitmapDecoder iconDecoder = new PngBitmapDecoder(iconStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
ImageSource iconSource = iconDecoder.Frames[0];
_icon.Source = iconSource;
Run Code Online (Sandbox Code Playgroud)
图标的定义如下: <Image x:Name="_icon" Width="16" Height="16" />
我对WPF有一个奇怪的问题,我在运行时从磁盘加载图像并将它们添加到StackView容器中.但是,图像未显示.经过一些调试我找到了诀窍,但它确实没有任何意义.我制作了一个小型演示应用程序来识别问题:
创建一个新的WPF项目,并粘贴代码如下:
XAML:
<Window x:Class="wpfBug.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300" Loaded="Window_Loaded">
<StackPanel Name="sp">
</StackPanel>
</Window>
Run Code Online (Sandbox Code Playgroud)
xaml.cs,粘贴在默认值下面:
namespace wpfBug
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Image i = new Image();
BitmapImage src = new BitmapImage();
src.BeginInit();
src.UriSource = new Uri("picture.jpg", UriKind.Relative);
src.EndInit();
i.Source = src;
i.Stretch = Stretch.Uniform;
//int q = src.PixelHeight; // Image loads here
sp.Children.Add(i);
} …Run Code Online (Sandbox Code Playgroud)