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 图像吗?

4

3 回答 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 窗体类。如果您坚持将图像嵌入到您的程序集中,则需要以下更冗长的代码来加载图像:

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;
}
于 2012-06-30T18:40:16.513 回答
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();

点击这里查看参考

于 2012-06-30T18:30:43.607 回答
0

如果您使用的是 WPF,请右键单击项目中的图像并将其设置Build ActionResource. 假设您的图像被调用MyImage.jpg并且位于项目的Resources文件夹中,您应该能够直接在您的项目中引用它,xaml而无需使用任何 C# 代码。像这样:

<Image Source="/Resources/MyImage.jpg" 
    HorizontalAlignment="Left"
    Height="210" 
    Margin="35,10,0,0"
    VerticalAlignment="Top"
    Width="335">
</Image>
于 2012-06-30T18:37:54.260 回答