我有一个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); }
}
1 回答
虽然WPF项目中的图像资源在
Resources.Designer.cs
中生成System.Drawing.Bitmap
属性,但您可以直接从该资源创建BitmapImage . 您只需要将图像文件的Build Action设置为Resource
(而不是默认的None
) .如果Visual Studio项目的
Resources
文件夹中有Red.jpg
文件,则创建BitmapImage
将如下所示 . 它使用WPF Pack Uri .如果你有一个Image控件在XAML中的某处声明如下:
你可以简单地在后面的代码中将图像的
Source
属性设置为你的BitmapImage:如果您希望通过绑定设置
Source
属性,则可以创建一个返回图像URI的string
属性 . 该字符串将由WPF中的内置TypeConverter自动转换为BitmapImage
.在XAML中,您将绑定到该属性,如下所示:
当然你也可以声明属性为
ImageSource
类型并以相同的方式绑定:
现在,您可以预先加载图像并根据需要将它们放入属性中:
更新:毕竟,您的图像不需要是Visual Studio项目中的资源 . 您可以只添加一个项目文件夹,将图像文件放入该文件夹并将其Build Action设置为
Resource
. 例如,如果您调用文件夹Images
,则URI将为pack://application:,,,/Images/Red.jpg
.