如何用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 回答
jeck猫
TA贡献1909条经验 获得超7个赞
System.Drawing.Bitmap
Resources.Designer.cs
BitmapImage
Resource
None
).
Red.jpg
Resources
BitmapImage
var uri = new Uri("pack://application:,,,/Resources/Red.jpg");var bitmap = new BitmapImage(uri);
Image
<Image x:Name="image"/>
Source
image.Source = bitmap;
Source
string
BitmapImage
TypeConverter
public partial class MainWindow : Window{ public MainWindow() { InitializeComponent(); DataContext = this; ImageUri = "pack://application:,,,/Resources/Red.jpg"; } public static readonly DependencyProperty ImageUriProperty = DependencyProperty.Register("ImageUri", typeof(string), typeof(MainWindow)); public string ImageUri { get { return (string)GetValue(ImageUriProperty); } set { SetValue(ImageUriProperty, value); } }}
<Image Source="{Binding ImageUri}"/>
ImageSource
public static readonly DependencyProperty ImageProperty = DependencyProperty.Register("Image", typeof(ImageSource), typeof(MainWindow));public ImageSource Image{ get { return (ImageSource)GetValue(ImageProperty); } set { SetValue(ImageProperty, value); }}
<Image Source="{Binding Image}"/>
private ImageSource imageRed = new BitmapImage(new Uri("pack://application:,,,/Resources/Red.jpg"));private ImageSource imageBlue = new BitmapImage(new Uri("pack://application:,,,/Resources/Blue.jpg"));...Image = imageBlue;
Resource
Images
pack://application:,,,/Images/Red.jpg
.
添加回答
举报
0/150
提交
取消