OK,這裏是一個改進GetImageSource(更名,以反映其真正的目的)。
/// <summary>
/// Get an ImageSource from the ResourceDictionary referred to by the
/// <paramref name="uriDictionary"/>.
/// </summary>
/// <param name="keyName">The ResourceDictionary key of the ImageSource
/// to retrieve.</param>
/// <param name="uriDictionary">The Uri to the XAML file that holds
/// the ResourceDictionary.</param>
/// <returns><c>null</c> on failure, the requested <c>ImageSource</c>
/// on success.</returns>
/// <remarks>If the requested resource is an <c>Image</c> instead of
/// an <c>ImageSource</c>,
/// then the <c>image.Source</c> is returned.</remarks>
public static ImageSource GetImageSource(String keyName, Uri uriDictionary)
{
if (String.IsNullOrEmpty(keyName))
throw new ArgumentNullException("keyName");
if (null == uriDictionary)
throw new ArgumentNullException("uriDictionary");
ResourceDictionary imagesDictionary = new ResourceDictionary();
imagesDictionary.Source = uriDictionary;
var var = imagesDictionary[keyName];
Object blob = imagesDictionary[keyName];
Debug.WriteLine(String.Format(
"error: GetImageSource('{0}', '{1}')"
+ " value is: {2}",
keyName,
uriDictionary,
(null == blob) ? "null" : blob.GetType().FullName));
if (null != blob)
{
if (blob is ImageSource)
{
return blob as ImageSource;
}
if (blob is Image)
{
Image image = blob as Image;
return image.Source;
}
if (blob is System.Drawing.Image)
{
System.Drawing.Image dImage = blob as System.Drawing.Image;
MemoryStream mem = new MemoryStream();
dImage.Save(mem, System.Drawing.Imaging.ImageFormat.MemoryBmp);
mem.Position = 0;
BitmapDecoder decode = new BmpBitmapDecoder(
mem,
BitmapCreateOptions.None,
BitmapCacheOption.None);
return decode.Frames[0];
}
Debug.WriteLine(String.Format(
"error: GetImageSource('{0}', '{1}')"
+ " can't handle type: {2}",
keyName,
uriDictionary,
blob.GetType().FullName));
}
return null;
}
,並使用它,你會做這樣的:
String packText = String.Format("pack://application:,,,/{0};component/{1}",
Assembly.GetEntryAssembly().FullName,
"ImageDictionary.xaml");
Uri imageUri = new Uri(packText);
// or if you prefer:
// Uri imageUri = new Uri("file:///.../ImageDictionary.xaml");
//
ImageSource source = GetImageSource(imageKey, imageUri);
if (null != source)
{
this.Image.Source = source;
}
else
{
// bail ...
}
的Drawing.Image
情況下將處理BMP,PNG,JPG,GIF等,即使我用BmpBitmapDecoder
。但請注意,XAML圖像非常漂亮,但Drawing.Image
不。
-Jesse
它的工作方式,有沒有錯誤...但是,即使具有源集,Image控件顯示什麼...但感謝,我不得不去維護一些。 ;-) – smsware
Szymon,跑進一個可能是問題的弱點。如果您正在更新的圖像恰好是一個UI元素,並將其設置爲空,則與其父項的鏈接將丟失。總是設置圖像源,以便對象關係不會在那裏丟失。 –