我寫了一個應用程序,它從OS獲取文件圖標並綁定到它們,但由於System.Drawing.Icon對象不能在Image控件中用作ImageSource的控件,所以我不得不寫一個converter。運行時將圖標轉換爲ImageSource
找一下,我來到了下面的代碼,我現在用的那一刻在這之後:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Icon ico = (value as Icon);
Bitmap bits = ico.ToBitmap();
MemoryStream strm = new MemoryStream();
// add the stream to the image streams collection so we can get rid of it later
_imageStreams.Add(strm);
bits.Save(strm, System.Drawing.Imaging.ImageFormat.Png);
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.StreamSource = strm;
bitmap.EndInit();
// freeze it here for performance
bitmap.Freeze();
return bitmap;
}
和我有三個問題:
有沒有更好的解決方案,你可以建議?
什麼是最終關閉所使用的
MemoryStream
的最佳方式,因爲這裏的代碼是由綁定系統自動調用的? (他們從來沒有手動實例化,因爲您可能會注意到我正在將流添加到集合中,我在析構函數中將它們稱爲Close()
,但我認爲這不是一個好的解決方案)。與上一個問題相關的是,當我在函數結束之前嘗試關閉流時,即使我在此之前調用Stream.Flush(),圖像也會顯示爲空。爲什麼是這樣?
我儘量不使用的圖像文件,你可以在資源字典中添加圖像,然後使用DataTrigger來設置所需的圖像資源。如果你認爲你可以服務,放一些你的XAML代碼,我們可以申請 – Mate
感謝@Mate,我實際上是通過調用Icon.ExtractAssociatedIcon(path)來獲取圖標。所以我不能宣佈他們在前面。 –