问题
I am working on a C# WPF application, using .resx files for resource management. Now, I'm trying to add icons (.ico) to the project but I'm running into some problems.
<Image Name="imgMin" Grid.Column="0"
Stretch="UniformToFill"
Cursor="Hand"
MouseDown="imgMin_MouseDown">
<Image.Style>
<Style TargetType="{x:Type Image}">
<Setter Property="Source" Value="\Images\minimize_glow.ico"/>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Source" Value="\Images\minimize_glow.ico"/>
</Trigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
This works fine, but when I move the icon into AppResources.resx I run into problems with referencing it in the xaml code. What should I be using instead of the Setter Property=... lines above? This:
<Setter Property="Source" Value="{x:Static res:AppResources.minimize}"/>
doesn't work, I think I probably need to use a different Property than "Source" because Value isn't a string pointing to the icon but the icon itself now. I can't figure out which one to use though - some help, please?
回答1:
The Source
property does not "want" a string, it just converts it when it gets one. If you add an icon to the resources it will be of the type System.Drawing.Icon
. You will need to convert it to an ImageSource
via converter.
You can do a static access to resources but it needs to comply with the expected syntax of x:Static.
e.g.
xmlns:prop="clr-namespace:Test.Properties"
<Image MaxHeight="100" MaxWidth="100">
<Image.Source>
<Binding Source="{x:Static prop:Resources.icon}">
<Binding.Converter>
<vc:IconToImageSourceConverter/>
</Binding.Converter>
</Binding>
</Image.Source>
</Image>
public class IconToImageSourceConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var icon = value as System.Drawing.Icon;
var bitmap = icon.ToBitmap();
//http://stackoverflow.com/questions/94456/load-a-wpf-bitmapimage-from-a-system-drawing-bitmap/1069509#1069509
MemoryStream ms = new MemoryStream();
bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
ms.Position = 0;
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = ms;
bi.EndInit();
return bi;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
Notes:
- The resource access modifier must be public
- If the image is added as "Image" you end up with a
Bitmap
instead of an Icon, which requires a different converter
来源:https://stackoverflow.com/questions/5790617/how-to-reference-icons-inside-resx-files-from-xaml