我有一个需要向用户提供内部状态反馈的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); }
}