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

如何使用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); }
    }


一只斗牛犬
浏览 418回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP