如何用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.BitmapResources.Designer.csBitmapImageResourceNone).
Red.jpgResourcesBitmapImage
var uri = new Uri("pack://application:,,,/Resources/Red.jpg");var bitmap = new BitmapImage(uri);Image
<Image x:Name="image"/>
Source
image.Source = bitmap;
SourcestringBitmapImageTypeConverter
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;ResourceImagespack://application:,,,/Images/Red.jpg.
添加回答
舉報
0/150
提交
取消
