[英]How to bind images from Properties.Resources in Xaml?
I have some images added to Properties.Resources
, where I can access them like:我在
Properties.Resources
中添加了一些图像,我可以在其中访问它们,例如:
Properties.Resources.LayerIcon;
and want to use it in Xaml, but don't know how to do this.并想在Xaml中使用它,但不知道该怎么做。
I know there are different ways for images to be added into a WPF project, but I need to use Properties.Resources
, because that's the only way I found where the images show up, when the application is launched via reflection.我知道将图像添加到 WPF 项目中有不同的方法,但我需要使用
Properties.Resources
,因为这是我在通过反射启动应用程序时找到图像显示位置的唯一方法。
The images in Properties.Resources
are of type System.Drawing.Bitmap
, but WPF uses System.Windows.Media.ImageSource
. Properties.Resources
中的图像类型为System.Drawing.Bitmap
,但 WPF 使用System.Windows.Media.ImageSource
。 You can create a converter:您可以创建一个转换器:
[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();
}
}
And use it as follows:并按如下方式使用它:
<Image Source="{Binding Source={x:Static prop:Resources.LayerIcon}, Converter={StaticResource bitmapToImageSourceConverter}}" />
Make sure your Resource is set to public and not internal.确保您的资源设置为公共而不是内部。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.