我有一些图片添加到了Properties.Resources
中,我可以像这样访问它们:
Properties.Resources.LayerIcon;
我想在Xaml中使用图片,但不知道如何操作。我知道有不同的方法将图片添加到WPF项目中,但我需要使用
Properties.Resources
,因为这是我找到的唯一一种方法,在通过反射启动应用程序时,图片才会显示出来。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。
'System.Drawing.Bitmap' 不包含 'GetHBitmap' 的定义,并且找不到接受 'System.Drawing.Bitmap' 类型的第一个参数的扩展方法 'GetHBitmap'
。 - Joan VengeGetHbitmap
:O - Joan Venge