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中的图像来动态更改图像源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-29 01:01