2012-06-30 39 views
2

我有位图图像变量,我想将它绑定到我的xaml窗口。绑定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> 

u能帮助我的C#代码此位变量绑定到这个XAML的形象?

回答

4

如果你真的想从C#代码设置,而不是从内部XAML,你应该使用这个简单的解决方案described further on the MSDN reference

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; 
} 
+0

关键是我想让一个像幻灯片一样改变这张照片的计时器。我做了一个计时器,但我不知道如何通过C#代码更改图像 – user1493114

+0

好的,我试着用这个名字! – user1493114

+0

我发布的代码应该完全适用于这种情况。你需要一个例子吗? – Adam

1

下面是一些示例代码:

// 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

+0

感谢,内存流帮助了我很多! – user1493114

+0

不客气,感谢在这个论坛上的方式是加价或接受答案。 –

+0

为什么在有更直接简单的方法时使用'MemoryStream'并引用'System.Drawing.Image'? – Adam

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> 
+0

不是挑剔的,但是OP确实特别询问了如何在C#中完成这项工作。 – Adam