关于c#:绑定Xaml位图图像

Bind Xaml bitmap image

我有位图图像变量,我想将其绑定到我的xaml窗口。

1
2
3
4
5
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代码

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

您能协助我通过C#代码将此位图变量绑定到此xaml图像吗?


如果您确实想从C#代码而不是从XAML内部进行设置,则应使用MSDN参考上进一步描述的简单解决方案:

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

但首先,您需要给您的Image一个名称,以便可以从c#中引用它:

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

无需引用Windows窗体类。
如果坚持将图像嵌入到部件中,则需要以下更长的代码来加载图像:

1
2
3
4
5
6
7
8
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;
}


这是一些示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 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();

点击这里查看参考


如果使用WPF,请在项目中右键单击图像,然后将Build Action设置为Resource。 假设您的图像称为MyImage.jpg并且位于项目的Resources文件夹中,则应该可以在xaml中直接引用它,而无需使用任何C#代码。 像这样:

1
2
3
4
5
6
7
<Image Source="/Resources/MyImage.jpg"
    HorizontalAlignment="Left"
    Height="210"
    Margin="35,10,0,0"
    VerticalAlignment="Top"
    Width="335">
</Image>