为了账号安全,请及时绑定邮箱和手机立即绑定

如何用Properties.Resources中的图像从WPF中的代码隐藏动态更改图像源?

如何用Properties.Resources中的图像从WPF中的代码隐藏动态更改图像源?

缥缈止盈 2019-07-26 15:14:19
如何用Properties.Resources中的图像从WPF中的代码隐藏动态更改图像源?我有一个WPF应用程序,需要向用户提供关于内部状态的反馈。设计有三张图片,分别叫红色、黄色和绿色。这些图像中的一个将根据状态一次显示。以下是要点:这三个图像在Properties.Resources中一次只显示一幅图像。状态更改来自代码隐藏中的进程,而不是用户。我想绑定一个图像控件,这样我就可以从代码背后更改图像。我假设需要一个图像转换器将JPG图像更改为图像源,如:[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();     }}我倾向于在初始化期间转换一次图像,并保留图像源列表。我还假设需要一个依赖项属性来将控件绑定到,但我不知道如何使用以下图像源列表设置该属性:    // Dependancy Property for the North Image     public static readonly DependencyProperty NorthImagePathProperty         = DependencyProperty.Register(             "NorthImagePath",             typeof(ImageSource),             typeof(MainWindow),             new PropertyMetadata("**Don't know what goes here!!!**"));     // Property wrapper for the dependancy property     public ImageSource NorthImagePath     {         get { return (ImageSource)GetValue(NorthImagePathProperty); }         set { SetValue(NorthImagePathProperty, value); }     }
查看完整描述

2 回答

?
红糖糍粑

TA贡献1815条经验 获得超6个赞

这应该也适用于PNG文件。也许您不应该将它们作为资源添加到您的项目中(请参阅我的编辑)。只需使用您最喜欢的图像工具创建文件,并将它们添加到项目中的文件夹中即可。看见这里关于接受。



查看完整回答
反对 回复 2019-07-27
  • 2 回答
  • 0 关注
  • 495 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信