如何使用 Properties.Resources 中的图像从 WPF 中的代码隐藏动态更改图像源? [英] How do I change an image source dynamically from code-behind in WPF with an image in Properties.Resources?

查看:20
本文介绍了如何使用 Properties.Resources 中的图像从 WPF 中的代码隐藏动态更改图像源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 WPF 应用程序,需要向用户提供有关内部状态的反馈.设计是有三个图像,分别称为红色、黄色和绿色.这些图像之一将根据状态一次显示.要点如下:

I have a WPF application that needs to provide feedback to the user about an internal state. The design is to have three images, call them Red, Yellow, and Green. One of these images will be displayed at a time depending on the state. Here are the points:

  • 这三个图像在代码隐藏的 Properties.Resources 中
  • 一次只会显示一张图片.
  • 状态更改来自代码隐藏过程,而不是来自用户.
  • 我想绑定一个图像控件,以便我可以从代码隐藏中更改图像.

我假设我需要一个图像转换器来将 JPG 图像更改为图像源,例如:

I’m assuming I’ll need an image converter to change the JPG image to an image source such as:

[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();
    }
}

<小时>

我更喜欢在初始化期间转换一次图像并保留图像源列表.我还假设我需要一个依赖属性来绑定控件,但我不确定如何使用此图像源列表进行设置:


I’d prefer to convert the images once during initialization and keep a list of Image sources. I’m also assuming I’ll need a dependency property to bind the control to, but I’m not sure how to set that up with this list of image sources:

    // 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); }
    }

推荐答案

虽然 WPF 项目中的图像资源会在 Resources.Designer.cs<中生成 System.Drawing.Bitmap 属性/code>,您可以直接从该资源创建 BitmapImage.您只需要将图像文件的Build Action设置为Resource(而不是默认的None).

Although an image resource in a WPF project generates a System.Drawing.Bitmap property in Resources.Designer.cs, you could directly create a BitmapImage from that resource. You only need to set the Build Action of the image file to Resource (instead of the default None).

如果您在 Visual Studio 项目的 Resources 文件夹中有一个文件 Red.jpg,则创建一个 BitmapImage 将如下所示.它使用 WPF Pack Uri.

If you have a file Red.jpg in the Resources folder of your Visual Studio Project, creating a BitmapImage would look like shown below. It uses a WPF Pack Uri.

var uri = new Uri("pack://application:,,,/Resources/Red.jpg");
var bitmap = new BitmapImage(uri);

如果您在 XAML 中的某处声明了 Image 控件像这样:

If you have an Image control declared somewhere in XAML like this:

<Image x:Name="image"/>

您可以简单地将图像的 Source 属性设置为您的 BitmapImage 在后面的代码中:

you could simply set the Source property of the image to your BitmapImage in code behind:

image.Source = bitmap;

<小时>

如果您更喜欢通过绑定来设置 Source 属性,您可以创建一个返回图像 URI 的 string 属性.该字符串将通过内置的 BitmapImage>TypeConverter 在 WPF 中.


In case you prefer to set the Source property by binding you could create a string property that returns the image URI. The string will automatically be converted to a BitmapImage by a built-in TypeConverter in WPF.

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); }
    }
}

在 XAML 中,您可以像这样绑定到该属性:

In XAML you would bind to that property like this:

<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}"/>

现在您可以预加载图像并根据需要将它们放入属性中:

Now you could pre-load your images and put them into the property as needed:

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;

<小时>

更新:毕竟,您的图像不需要是 Visual Studio 项目中的资源.您可以只添加一个项目文件夹,将图像文件放入该文件夹并将其构建操作设置为 Resource.例如,如果您调用文件夹 Images,则 URI 将是 pack://application:,,,/Images/Red.jpg.


UPDATE: After all, your images do not need to be resources in the Visual Studio project. You could just add a project folder, put the image files into that folder and set their Build Action to Resource. If for example you call the folder Images, the URI would be pack://application:,,,/Images/Red.jpg.

这篇关于如何使用 Properties.Resources 中的图像从 WPF 中的代码隐藏动态更改图像源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆