如何绑定Xaml中Properties.Resources的图像?

Joa*_*nge 2 .net c# wpf xaml image

我添加了一些图像Properties.Resources,我可以在其中访问它们:

Properties.Resources.LayerIcon;
Run Code Online (Sandbox Code Playgroud)

并希望在Xaml中使用它,但不知道如何做到这一点.

我知道将图像添加到WPF项目中有不同的方法,但我需要使用Properties.Resources,因为这是我通过反射启动应用程序时图像显示的唯一方法.

Tho*_*que 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

并使用如下:

<Image Source="{Binding Source={x:Static prop:Resources.LayerIcon}, Converter={StaticResource bitmapToImageSourceConverter}}" />
Run Code Online (Sandbox Code Playgroud)

确保您的资源设置为公共资源而非内部资源.

  • 啊,是的,默认情况下,资源被声明为内部... BTW,不要手动编辑Resources.resx.cs文件,如果更改资源,它将被覆盖.将自定义工具从ResxFileCodeGenerator更改为PublicResxFileCodeGenerator (2认同)