如何从XAML中引用.resx文件内的图标?

10

我正在开发一个使用.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>

这个代码运行良好,但是当我把图标移动到AppResources.resx中时,在xaml代码中引用它就会遇到问题。在上面的Setter Property = ...行中,我应该使用什么代替?是这样的:

<Setter Property="Source" Value="{x:Static res:AppResources.minimize}"/>

这不起作用,我认为我可能需要使用与“Source”不同的属性,因为现在“Value”不是指向图标的字符串,而是图标本身。然而,我无法弄清楚应该使用哪个属性 - 求助?

1个回答

3
Source属性并不要求一个字符串,只是在获取到字符串时将其转换。如果您向资源中添加图标,则该图标将是System.Drawing.Icon类型。您需要通过转换器将其转换为ImageSource

您可以对资源进行静态访问,但必须符合x:Static的预期语法。

例如:

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();

        //https://dev59.com/1XVD5IYBdhLWcg3wE3bz#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();
    }
}

注意事项:

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

非常有用...我想。现在出现了一个错误,提示:未知的构建错误,“Key cannot be null. Parameter name: key Line 131 Position 34.”指向Binding Source="{x:Static res:AppResources.minimize}" - Swooper
不,我刚刚在一个新的.NET 3.5项目中测试了它,它可以工作。 - H.B.
嗯,没想到会是这个问题。但是现在我又遇到了一个奇怪的错误:未找到类型“Helpers:IconToImageSourceConverter”。请确认您没有丢失程序集引用,并且所有引用的程序集都已构建。 我在代码后台中有正确的using行,xmlns:Helpers指向正确的命名空间...这是怎么回事? - Swooper
代码后台不重要,只有“xmlns”很重要。当然,类应该是公共的。 - H.B.
顺便提一下,我仍然会收到“键不能为空”的错误。也许它们在某种程度上是相互关联的... - Swooper
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接