如何在Xaml中绑定来自Properties.Resources的图片?

3

我有一些图片添加到了Properties.Resources中,我可以像这样访问它们:

Properties.Resources.LayerIcon;

我想在Xaml中使用图片,但不知道如何操作。我知道有不同的方法将图片添加到WPF项目中,但我需要使用Properties.Resources,因为这是我找到的唯一一种方法,在通过反射启动应用程序时,图片才会显示出来。
1个回答

10

Properties.Resources中的图像是System.Drawing.Bitmap类型,但WPF使用System.Windows.Media.ImageSource。您可以创建一个转换器:

[ValueConversion(typeof(System.Drawing.Bitmap), typeof(ImageSource))]
public class BitmapToImageSourceConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var bmp = value as System.Drawing.Bitmap;
        if (bmp == null)
            return null;
        return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                    bmp.GetHbitmap(),
                    IntPtr.Zero,
                    Int32Rect.Empty,
                    BitmapSizeOptions.FromEmptyOptions());
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

然后按以下方式使用它:

<Image Source="{Binding Source={x:Static prop:Resources.LayerIcon}, Converter={StaticResource bitmapToImageSourceConverter}}" />

确保您的资源已设置为 public 而非 internal。


谢谢,您从哪里获得了GetHBitmap? 这是我应该添加的非托管方法吗? - Joan Venge
感谢您,但由于某些原因我遇到了这个错误:'System.Drawing.Bitmap' 不包含 'GetHBitmap' 的定义,并且找不到接受 'System.Drawing.Bitmap' 类型的第一个参数的扩展方法 'GetHBitmap' - Joan Venge
好的,我明白了,那是一个打字错误,应该是 GetHbitmap :O - Joan Venge
2
啊,是的,默认情况下资源被声明为 internal(内部)... 顺便说一句,不要手动编辑 Resources.resx.cs 文件,如果你更改了资源,它将被覆盖。将自定义工具从 ResxFileCodeGenerator 更改为 PublicResxFileCodeGenerator。 - Thomas Levesque
@sky,在你的项目中的一个 C# 文件中,就像任何其他类一样。 - Thomas Levesque
显示剩余7条评论

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