How to load image to WPF in runtime?

Viewed 114934

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

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

Wonder because I have seen examples with sorces to the images inside the XAML tags.

EDIT:

I'm using this now:

var uri = new Uri("pack://application:,,,/sas.png");
var bitmap = new BitmapImage(uri);
image1.Source = bitmap;

The 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>

EDIT 2: My issue is solved, this code works fine:

BitmapImage image = new BitmapImage(
    new Uri("pack://application:,,,/Resources/" + company + ".png"));
image2.Source = image;
2 Answers
Related