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

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

问题描述

我有一个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属性,但是您可以直接创建 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 Project的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属性.内置的 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.

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

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