如何在xaml中引用.resx文件中的图标?

Swo*_*per 10 .net c# data-binding wpf icons

我正在使用.resx文件进行资源管理的C#WPF应用程序.现在,我正在尝试向项目添加图标(.ico),但我遇到了一些问题.

<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>
Run Code Online (Sandbox Code Playgroud)

这工作正常,但是当我将图标移动到AppResources.resx时,我遇到了在xaml代码中引用它的问题.我应该使用什么而不是上面的Setter Property = ...行?这个:

<Setter Property="Source" Value="{x:Static res:AppResources.minimize}"/>
Run Code Online (Sandbox Code Playgroud)

不起作用,我想我可能需要使用与"Source"不同的Property,因为Value不是指向图标的字符串,而是现在的图标本身.我无法弄清楚使用哪一个 - 请帮助一下?

H.B*_*.B. 3

Source属性并不“想要”一个字符串,它只是在获得字符串时对其进行转换。如果将图标添加到资源中,它将属于 类型System.Drawing.Icon。您需要将其转换为ImageSource通过转换器。

您可以对资源进行静态访问,但它需要符合x:Static.

例如

xmlns:prop="clr-namespace:Test.Properties"
Run Code Online (Sandbox Code Playgroud)
xmlns:prop="clr-namespace:Test.Properties"
Run Code Online (Sandbox Code Playgroud)
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();
    }
}
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 资源访问修饰符必须是公共的
  • 如果将图像添加为“图像”,您最终会得到一个Bitmap而不是图标,这需要不同的转换器