2011-12-28 132 views
3

我在WCF服務以下代碼:[ImageMember]如何與Image一起使用?

[DataContract] 
[KnownType(typeof(Bitmap))] 
[KnownType(typeof(Image))] 
public class CompositeType { 
Image FImg = null; 
public Image Picture { 
    get { 
    return FImg; 
    } 
    set { 
    FImg = value; 
    } 
} 

如果我添加[數據成員]向公衆圖像,則服務引用被在另一種解決方案打破。

[DataMember] 
public Image Picture{ 
    get { 
    return FImg; 
    } 
    set { 
    FImg = value; 
    } 
} 

我的問題是如何在同一時間使用[DataMember]和圖像?我知道我可以使用一個字節數組,並且目前正在這樣做,然後在調用我的服務的客戶端中格式化/轉換它,但我寧願綁定到Image,而不必轉換字節數組。

+0

可能重複[在WCF我怎麼返回一個類,包含一個System.Drawing.Image屬性?](http://stackoverflow.com/questions/1767864/in-wcf-how-do-i-return-a-class-that-c​​ontains-a-system-drawing-image -property) – Yuck

+0

@Yuck - 與此類似。實際上我之前讀過這篇文章,目前正在使用與轉換爲字節數組和將其標記爲DataMember相關的部分答案。但是,我試圖找到一種方法來不必創建字節數組。 – David

+0

從這個問題的接受答案:*「無論如何,你需要把它變成一個字節[]或流,以通過電線,並補充它作爲一個圖像。」* – Yuck

回答

0

我發現在客戶端使用AutoGeneratingColumn事件句柄(調用我的WCF服務的Silverlight應用程序)也適用。不一定是我的問題的答案,但我認爲這是有用的知道。我會添加評論,但代碼太長。

private void dgResults_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e) { 
     if (e.PropertyType == typeof(byte[])) { 
     e.Column.Header = e.Column.Header + "_D"; 
     // Create a new template column. 
     DataGridTemplateColumn templateColumn = new DataGridTemplateColumn(); 
     templateColumn.Header = e.Column.Header + "_E"; 
     templateColumn.CellTemplate = (DataTemplate)Resources["imgTemplate"]; 
     templateColumn.CellEditingTemplate = (DataTemplate)Resources["imgTemplate"]; 
     // ... 
     // Replace the auto-generated column with the templateColumn. 
     e.Column = templateColumn; 

     } 
    } 

參考資料[「imgTemplate」在Silverlight中.XAML文件被創建和驗證碼是其代碼隱藏。

<UserControl.Resources> 
    <local:BinaryArrayToURIConverter x:Key="binaryArrayToURIConverter" /> 
    <DataTemplate x:Key="imgTemplate"> 
     <Image x:Name="img" Source="{Binding GraphicBytes,Converter={StaticResource binaryArrayToURIConverter}}"/> 
    </DataTemplate> 
    </UserControl.Resources> 

地方:指主XAML聲明的一部分:

xmlns:local="clr-namespace:<your namespace here>" 

爲BinaryArrayToURIConverter代碼:

public class BinaryArrayToURIConverter : IValueConverter { 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { 
     MemoryStream ms = new MemoryStream((byte[])value); 
     BitmapImage image = new BitmapImage(); 
     image.SetSource(ms); 
     return image; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { 
     throw new NotImplementedException(); 
    } 
    } 
相關問題