他の誰かがこれを行う方法を見つけたと確信しています。私は近いですが、完全ではありません。StaticResourceConverter クラスを使用して、リソース名に基づいてリソースにバインドされた Geometry を持つ Path オブジェクトを正常に使用できます。
public class StaticResourceConverter: BaseConverter, IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if(System.Convert.ToString(value).IsNullOrEmpty())
{
return null;
}
var resource = Application.Current.Resources[value];
return resource;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new Exception("The method or operation is not implemented.");
}
}
MenuItem で Image オブジェクトにバインドするには、同じメソッドを使用して、基になる DrawingImage を使用して Image のインスタンスを作成する必要があります。
<Style TargetType="{x:Type MenuItem}">
<Setter Property="Icon">
<Setter.Value>
<Image Style="{StaticResource ResourceKey=SpMenuItemIcon}">
<Image.Source>
<DrawingImage>
<DrawingImage.Drawing>
<GeometryDrawing
Brush="{StaticResource SpIconPath}"
Geometry="{Binding IconPath,
Converter={converters:StaticResourceConverter}}"/>
</DrawingImage.Drawing>
</DrawingImage>
</Image.Source>
</Image>
</Setter.Value>
</Setter>
</Style>
問題は、メニューの最後のアイコンのみが正しいジオメトリ パスで表示されるため、Image のインスタンスが 1 つだけ作成されるか、1 つだけがバインドされていると思われることです。WPF が最後の MenuItem のみをバインドする理由と、すべてのメニュー項目で動作させる方法を教えてください。
アップデート:
ここでのテストを支援するために、(キーを使用して) バインドするいくつかのジオメトリ リソースの例を示します。
<Geometry x:Key="ExpandIconPath">F1 M 30.25,58L 18,58L 18,45.75L 22,41.75L 22,50.75L 30,42.75L 33.25,46L 25.25,54L 34.25,54L 30.25,58 Z M 58,45.75L 58,58L 45.75,58L 41.75,54L 50.75,54L 42.75,46L 46,42.75L 54,50.75L 54,41.75L 58,45.75 Z M 45.75,18L 58,18L 58,30.25L 54,34.25L 54,25.25L 46,33.25L 42.75,30L 50.75,22L 41.75,22L 45.75,18 Z M 18,30.25L 18,18L 30.25,18L 34.25,22L 25.25,22L 33.25,30L 30,33.25L 22,25.25L 22,34.25L 18,30.25 Z</Geometry>
<Geometry x:Key="CollapseIconPath">F1 M 54.2499,34L 42,34L 42,21.7501L 45.9999,17.7501L 45.9999,26.7501L 53.9999,18.7501L 57.2499,22.0001L 49.2499,30.0001L 58.2499,30.0001L 54.2499,34 Z M 34,21.7501L 34,34L 21.75,34L 17.75,30.0001L 26.75,30.0001L 18.75,22.0001L 22,18.7501L 30,26.7501L 30,17.7501L 34,21.7501 Z M 21.75,42L 34,42L 34,54.25L 30,58.25L 30,49.25L 22,57.25L 18.75,54L 26.75,46L 17.75,46L 21.75,42 Z M 42,54.25L 42,42L 54.2499,42L 58.2499,46L 49.2499,46.0001L 57.2499,54L 53.9999,57.25L 45.9999,49.25L 45.9999,58.25L 42,54.25 Z</Geometry>
<Geometry x:Key="CloseIconPath">F1 M 26.9166,22.1667L 37.9999,33.25L 49.0832,22.1668L 53.8332,26.9168L 42.7499,38L 53.8332,49.0834L 49.0833,53.8334L 37.9999,42.75L 26.9166,53.8334L 22.1666,49.0833L 33.25,38L 22.1667,26.9167L 26.9166,22.1667 Z</Geometry>