如何在运行时将图像加载到 WPF? [英] How to load image to WPF in runtime?
问题描述
在运行时将图像加载到 WPF 窗口似乎相当复杂.
It seems like it's quite complicated to load an image in runtime to a WPF window.
Image image;
image = new Uri("Bilder/sas.png", UriKind.Relative);
????.Source = new BitmapImage(image);
我正在尝试此代码,但我需要一些帮助才能使其正常工作.我在代码下方看到了一些红线!我还想知道我是否需要在 XAML 代码中添加一些额外的代码,或者是否足够:
I'm trying this code, but I need some help to get it to work. I get some red lines below the code! I also wonder if I need to add some extra code inside the XAML code or is in enough with this:
<Image Height="200" HorizontalAlignment="Left" Margin="12,12,0,0" Name="image1"
Stretch="Fill" VerticalAlignment="Top" Width="350" />
很奇怪,因为我看到过 XAML 标签内的图像来源示例.
Wonder because I have seen examples with sorces to the images inside the XAML tags.
我现在正在使用它:
var uri = new Uri("pack://application:,,,/sas.png");
var bitmap = new BitmapImage(uri);
image1.Source = bitmap;
XAML:
<Grid Width="374">
<Image Height="200" HorizontalAlignment="Left" Margin="12,12,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="350" />
<Button Content="Start" Height="23" HorizontalAlignment="Left" Margin="12,226,0,0" Name="btnStart" VerticalAlignment="Top" Width="75" />
<Button Content="Land" Height="23" HorizontalAlignment="Left" Margin="287,226,0,0" Name="btnLand" VerticalAlignment="Top" Width="75" />
<ComboBox Height="23" HorizontalAlignment="Left" Margin="110,226,0,0" Name="cmbChangeRoute" VerticalAlignment="Top" Width="156" />
</Grid>
编辑 2:我的问题解决了,这段代码工作正常:
EDIT 2: My issue is solved, this code works fine:
BitmapImage image = new BitmapImage(
new Uri("pack://application:,,,/Resources/" + company + ".png"));
image2.Source = image;
推荐答案
In WPF an image is typically loaded from a Stream or an Uri.
BitmapImage 支持两者,甚至可以将 Uri 作为构造函数参数传递:
BitmapImage supports both and an Uri can even be passed as constructor argument:
var uri = new Uri("http://...");
var bitmap = new BitmapImage(uri);
如果图像文件位于本地文件夹中,则必须使用 file://
Uri.您可以从这样的路径创建这样的 Uri:
If the image file is located in a local folder, you would have to use a file://
Uri. You could create such a Uri from a path like this:
var path = Path.Combine(Environment.CurrentDirectory, "Bilder", "sas.png");
var uri = new Uri(path);
如果图像文件是程序集资源,则 Uri 必须遵循 打包 Uri 方案:
If the image file is an assembly resource, the Uri must follow the the Pack Uri scheme:
var uri = new Uri("pack://application:,,,/Bilder/sas.png");
在这种情况下,sas.png
的 Visual Studio 构建操作必须是 Resource
.
In this case the Visual Studio Build Action for sas.png
would have to be Resource
.
一旦你创建了一个 BitmapImage
并且还有一个 Image 控件就像在这个 XAML 中
Once you have created a BitmapImage
and also have an Image control like in this XAML
<Image Name="image1" />
您只需将 BitmapImage 分配给该 Image 控件的 Source
属性:
you would simply assign the BitmapImage to the Source
property of that Image control:
image1.Source = bitmap;
这篇关于如何在运行时将图像加载到 WPF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!