2011-03-06 49 views
0

我試圖從PicSet1.dll中將一些圖片轉換爲WPF圖像控件。我不知道如何將位圖放入控件中。在圖像類中看不到任何方法。如何將位圖對象放在圖像控制中的wpf處理對象時與Uri相對

 System.Reflection.AssemblyName aName; 
     aName = System.Reflection.AssemblyName.GetAssemblyName("c:\\PicSet1.dll"); 
     asm = System.Reflection.Assembly.Load(aName); 
     var result = asm.GetManifestResourceNames(); 
     var bitmap= new System.Drawing.Bitmap(asm.GetManifestResourceStream(res[0])); 
     image1 = bitmap. 
+0

你在你的DLL有什麼類型的圖像?它是如何編譯的(resx,build action,...)? – madd0 2011-03-06 11:26:20

+0

jpg's。構建行動嵌入式資源 – bkarj 2011-03-06 13:30:03

回答

0

一旦從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"); 
     } 
    } 
    } 
}