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 |
但首先,您需要给您的
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,请在项目中右键单击图像,然后将
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> |