一旦從DLL加載圖像,就可以將XAML中的圖像綁定到ImageSource。
關鍵是要確保參考DLL中的圖像具有Build Action = Embedded Resource。
這裏是XAML:
<Window x:Class="LoadImage.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Image Grid.Row="0" Grid.Column="0" Source="{Binding EmbeddedPicture}"/>
</Grid>
</Window>
這裏是視圖模型:
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace LoadImage.ViewModel
{
public class MainViewModel : ViewModelBase
{
public MainViewModel()
{
System.Reflection.AssemblyName aName;
aName = System.Reflection.AssemblyName.GetAssemblyName("PicSet1.dll");
if (aName != null)
{
Assembly asm = System.Reflection.Assembly.Load(aName);
if (asm != null)
{
string[] resources = asm.GetManifestResourceNames();
if ((resources != null) && (resources.Length > 0))
{
string name = resources[0];
if (!string.IsNullOrEmpty(name))
{
using (Stream myImage = asm.GetManifestResourceStream(name))
{
if (myImage != null)
{
using (System.Drawing.Image photo = System.Drawing.Image.FromStream((Stream) myImage))
{
MemoryStream finalStream = new MemoryStream();
photo.Save(finalStream, ImageFormat.Png);
// translate to image source
PngBitmapDecoder decoder = new PngBitmapDecoder(finalStream,
BitmapCreateOptions.PreservePixelFormat,
BitmapCacheOption.Default);
EmbeddedPicture = decoder.Frames[0];
}
}
}
}
}
}
}
}
private ImageSource _embeddedPicture;
public ImageSource EmbeddedPicture
{
get
{
return _embeddedPicture;
}
set
{
_embeddedPicture = value;
OnPropertyChanged("EmbeddedPicture");
}
}
}
}
你在你的DLL有什麼類型的圖像?它是如何編譯的(resx,build action,...)? – madd0 2011-03-06 11:26:20
jpg's。構建行動嵌入式資源 – bkarj 2011-03-06 13:30:03