绑定Xaml位图图像

3
我有一个位图图像变量,我想将它绑定到我的XAML窗口。
System.Reflection.Assembly thisExe;
        thisExe = System.Reflection.Assembly.GetExecutingAssembly();
        string[] resources = thisExe.GetManifestResourceNames();
        var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("SplashDemo.Resources.Untitled-100000.png");
        Bitmap image = new Bitmap(stream);

这是我的 XAML 代码:

<Image Source="{Binding Source}" HorizontalAlignment="Left"  Height="210" Margin="35,10,0,0" VerticalAlignment="Top" Width="335">
    </Image>

你能帮我通过C#代码将这个位图变量绑定到这个XAML图像中吗?
3个回答

8

如果你想从C#代码中设置它而不是在XAML内部设置,你应该使用这个简单的解决方案(在MSDN参考上进一步描述)

string path = "Resources/Untitled-100000.png";
BitmapImage bitmap = new BitmapImage(new Uri(path, UriKind.Relative));
image.Source = bitmap;

但是首先,您需要给Image命名,以便您可以从C#中引用它:

<Image x:Name="image" ... />

不需要引用Windows Forms类。如果你坚持将图像嵌入到程序集中,你需要以下更长的代码来加载图像:

string path = "SplashDemo.Resources.Untitled-100000.png";
using (Stream fileStream = GetType().Assembly.GetManifestResourceStream(path))
{
    PngBitmapDecoder bitmapDecoder = new PngBitmapDecoder(fileStream,
        BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
    ImageSource imageSource = bitmapDecoder.Frames[0];
    image.Source = imageSource;
}

重点是我想制作一个计时器,像幻灯片一样更改这张图片。我已经制作了一个计时器,但我不知道如何通过C#代码更改图像。 - user1493114
我发布的代码应该在那种情况下正常工作。你需要一个例子吗? - Adam
1
好的,请问如果图像嵌入到程序集中呢? - user1493114
1
我找到了解决方案,如果你想将 BuildAction 设置为 EmbeddedResource。发布中。 - Adam
没有足够的声望,我会在获得足够声望后投票支持那些现在和将来帮助我的答案 :) - user1493114
显示剩余2条评论

2

这里是一些示例代码:

// Winforms Image we want to get the WPF Image from...
System.Drawing.Image imgWinForms = System.Drawing.Image.FromFile("test.png");

// ImageSource ...
BitmapImage bi = new BitmapImage();
bi.BeginInit();
MemoryStream ms = new MemoryStream();

// Save to a memory stream...
imgWinForms.Save(ms, ImageFormat.Bmp);

// Rewind the stream...    
ms.Seek(0, SeekOrigin.Begin);

// Tell the WPF image to use this stream...
bi.StreamSource = ms;
bi.EndInit();

Click here to view reference


欢迎您的到来,此论坛感谢方式为点赞或接受回答。 - Ebad Masood
为什么要使用MemoryStream和引用System.Drawing.Image,当有更直接和简单的方法呢? - Adam

0
如果您正在使用WPF,请右键单击项目中的图像,然后将“生成操作”设置为“资源”。 假设您的图像名为“ MyImage.jpg”,并且位于项目中的“ Resources”文件夹中,则可以直接在XAML中引用它,而无需使用任何C#代码。 就像这样:
<Image Source="/Resources/MyImage.jpg" 
    HorizontalAlignment="Left"
    Height="210" 
    Margin="35,10,0,0"
    VerticalAlignment="Top"
    Width="335">
</Image>

不是挑刺,但是原帖确实特别询问了如何在C#中完成这个操作。 - Adam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接