一种可能性是使用IValueConverter
转换RoutedCommands
为的 a Images
。然后IValueConverter
可以在全局样式中使用。
XAML 如下所示:
<Style x:Key="MenuItemBase_Style" TargetType="{x:Type MenuItem}">
<Setter Property="Icon" Value="{Binding Command,Converter={StaticResource CommandImage_ValueConverter},RelativeSource={RelativeSource Mode=Self}}"/>
</Style>
<Style x:Key="CutMenuItem_Style" BasedOn="{StaticResource MenuItemBase_Style}" TargetType="{x:Type MenuItem}" >
<Setter Property="Command" Value="Cut"/>
</Style>
<Style x:Key="CopyMenuItem_Style" BasedOn="{StaticResource MenuItemBase_Style}" TargetType="{x:Type MenuItem}" >
<Setter Property="Command" Value="Copy"/>
</Style>
<Style x:Key="AnotherMenuItem_Style" ... />
IValueConverter很简单,但也可以针对其他事物进行扩展。我已经这样写了,您可以提供 aStyle
作为参数。如果您想操作返回的Image
.
public class CommandImageValueConverter : IValueConverter{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
if (value == null) return null;
var cmd = value as RoutedCommand;
if (null != cmd) {
var uri = new Uri("/YourComponent;component/Image/" + cmd.Name + "_16_16.png", UriKind.Relative);
return new Image() { Stretch = Stretch.None ,Source=Load(uri),Style=parameter as Style};
}
throw new NotImplementedException("Conversion from " + value.GetType().Name + " is currently not supported");
}
public static ImageSource Load(Uri uri) {
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.UriSource = uri;
bi.EndInit();
return bi;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
throw new NotImplementedException();
}
}
IValueConverter
也必须声明一次:
<yourNamespace:CommandImageValueConverter x:Key="CommandImage_ValueConverter"/>
希望这对其他人有帮助。