2013-02-06 55 views
1

我想綁定圖像控件中的字節[],但在轉換器中存在一些問題。請讓我知道我該如何解決這個問題? 由於byte []中沒有AsBuffer函數,因此我得到了行stream.WriteAsync(bytesArray.AsBuffer());的錯誤。我應該如何解決這個問題?Windows 8 XAML將字節[]綁定到圖像控件?

代碼:

public object Convert(object value, Type targetType, object parameter, string language) 
     { 
      byte[] bytesArray; 

      if (value != null && value is byte[] && (value as byte[]).Length > 0) 
      { 
       bytesArray = value as byte[]; 
      } 
      else 
      { 
       //TODO: Add default Image here 
      } 

      using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream()) 
      { 
       BitmapImage image = new BitmapImage(); 
       stream.WriteAsync(bytesArray.AsBuffer()); 
       stream.Seek(0); 
       image.SetSource(stream); 
       return image; 
      } 
     } 

XAML代碼:

<Image Source="{Binding Path=OnlineBooksDetail[0].ImageSource, Converter={StaticResource ByteToBitmapImageConverter}}" Width="407" Height="542"> 
         </Image> 
+0

在WPF中,您可以直接將'byte []'綁定到'Source',這在WindowsRuntime中不起作用嗎? –

+0

好的,這就是爲什麼我需要一個轉換器。你可以提供一些幫助更新我已經寫的或者其他方式來實現這一目標嗎? –

+0

我不熟悉WindowsRuntime,不知道里面有什麼,它有'MemoryStream' –

回答

2

我能夠通過如下書面創建轉換器,以解決這一問題。以下是工作。無論如何,請讓我知道我是否可以改進它。

代碼: BitmapImage image;

/// <summary> 
    /// Converts the specified value. 
    /// </summary> 
    /// <param name="value">The value.</param> 
    /// <param name="targetType">Type of the target.</param> 
    /// <param name="parameter">The parameter.</param> 
    /// <param name="language">The language.</param> 
    /// <returns></returns> 
    public object Convert(object value, Type targetType, object parameter, string language) 
    { 
     byte[] bytesArray = null; 

     if (value != null && value is byte[] && (value as byte[]).Length > 0) 
     { 
      bytesArray = value as byte[]; 
     } 
     else 
     { 
      //TODO: Add default Image here 
     } 

     using (MemoryRandomAccessStream memoryStream = new MemoryRandomAccessStream(bytesArray)) 
     { 
      this.image = new BitmapImage(); 
      this.SetImageSource(memoryStream); 
      return image; 
     } 
    } 

    /// <summary> 
    /// Sets the image source. 
    /// </summary> 
    /// <param name="memoryStream">The memory stream.</param> 
    /// <exception cref="System.NotImplementedException"></exception> 
    private async void SetImageSource(MemoryRandomAccessStream memoryStream) 
    { 
     await this.image.SetSourceAsync(memoryStream); 
    } 
相關問題