2011-09-13 170 views
0

我需要找到將圖像保存到IsolatedStorage並向他們顯示的方式Silverlight(XAML) 重要提示:Silverlight必須拍攝「自己」圖像,我無法設置圖像從後面的代碼 我以前嘗試過很多解決方案。 的最後的解決方案是,結合字節數組,並將它們轉換爲圖像 XAMLWindows Phone 7從IsolatedStorage Silverlight綁定圖像

StackPanel Orientation="Horizontal" Margin="0,0,0,20"> 
           <Image Width="110" CacheMode="BitmapCache" Source="{Binding ThumbLocal,Converter={StaticResource imgConverter}}" 
             Margin="12,0,9,0"/> 
           <StackPanel Width="311"> 

代碼背後

public byte[] ThumbLocal 
     { 
      get; 
      set; 
     } 


public class ByteImageConverter : IValueConverter 
    { 

      public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
     { 
      MemoryStream memStream = new MemoryStream((byte[])value); 
      memStream.Seek(0, SeekOrigin.Begin); 
      BitmapImage thumbLocal = new BitmapImage(); 
      thumbLocal.SetSource(memStream); 
      return thumbLocal; 
     } 
    } 

的一切工作,直到我保存byte[]到數據庫中,並試圖找回。 現在我可以看到將圖像保存爲IsolatedStorage的唯一選項,然後檢索並隱藏到byte[]。 這是「智能」解決方案嗎?

回答

1

首先,創建這個轉換器:如果您使用的MVVM

public class BinaryToImageSourceConverter : IValueConverter 
{ 

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     if (value != null && value is byte[]) 
     { 
      var bytes = value as byte[]; 
      var stream = new MemoryStream(bytes); 
      var image = new BitmapImage(); 

      image.SetSource(stream); 
      stream.Close(); 
      return image; 
     } 
     return null; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 

其次,綁定到你的byte []使用該轉換器,即: 查看:

<Image Source="{Binding IsolatedStorageImage, Converter={StaticResource BinaryToImageSourceConverter}}" x:Name="ScanImage"/> 

可以使財產在contrlol(prop片段)中輸入byte []並從isostorage中將圖像讀取到字節數組,然後將屬性值設置爲它。 如果您有更多問題,請隨時問我。