私はそのための簡単なマークアップ拡張機能を使用します。
/// <summary>
/// Simple extension for icon, to let you choose icon with specific size.
/// Usage sample:
/// Image Stretch="None" Source="{common:Icon /Controls;component/icons/custom.ico, 16}"
/// Or:
/// Image Source="{common:Icon Source={Binding IconResource}, Size=16}"
/// </summary>
public class IconExtension : MarkupExtension
{
private string _source;
public string Source
{
get
{
return _source;
}
set
{
// Have to make full pack URI from short form, so System.Uri recognizes it.
_source = "pack://application:,,," + value;
}
}
public int Size { get; set; }
public override object ProvideValue(IServiceProvider serviceProvider)
{
var decoder = BitmapDecoder.Create(new Uri(Source),
BitmapCreateOptions.DelayCreation,
BitmapCacheOption.OnDemand);
var result = decoder.Frames.SingleOrDefault(f => f.Width == Size);
if (result == default(BitmapFrame))
{
result = decoder.Frames.OrderBy(f => f.Width).First();
}
return result;
}
public IconExtension(string source, int size)
{
Source = source;
Size = size;
}
public IconExtension() { }
}
XAMLの使用法:
<Image Stretch="None"
Source="{common:Icon Source={Binding IconResource},Size=16}"/>
または
<Image Stretch="None"
Source="{common:Icon /ControlsTester;component/icons/custom-reports.ico, 16}" />
私は間違いをします。バインディングを使用してマークアップ拡張でプロパティを設定することはできません(したがって、 ) –
Nikolay
私はそれが大好きです。奇妙なWPFの問題...と私は、StackOverflowの質問と答え...エレガントなソリューションを見つける。非常に素晴らしい。 +1 – cplotts
これは、例えば 'ListBox'でいくつかのアイコンを使うときのパフォーマンスに影響しますか?デコードされたアイコンを_cache_にするといいでしょう。したがって、各アイコンのサイズに対して1つのデコードが必要です。 – JobaDiniz