1
<Image x:Name="pageImg" Margin="-19,-1,37,19" Source="/img/1.png" Stretch="Uniform"  />

The images property also set to Build Action = Resource and Copy Output Directory = Cope if newer

When the button get clicked the application crashes:

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
            pageImg.Source = new BitmapImage(new Uri(@"/img/2.png"));
        }

But when I pass C:\Users\myuser\Desktop\2.png instead of /img/2.png it works just fine.

Why this is happening?

Vlad
  • 115
  • 7
  • 1
    Possible duplicate of [Change image source in code behind - Wpf](http://stackoverflow.com/questions/3787137/change-image-source-in-code-behind-wpf) – J.H. Jul 21 '16 at 20:44
  • @J.H. Thanks it worked nicely. – Vlad Jul 21 '16 at 20:50

2 Answers2

2

An image resource file (with Build Action set to Resource) should be loaded by a Resource File Pack URI:

pageImg.Source = new BitmapImage(new Uri("pack://application:,,,/img/2.png"));

It is not necessary to get it copied to the output directory.

Clemens
  • 123,504
  • 12
  • 155
  • 268
0

This solved my problem :

pageImg.Source = new BitmapImage(new Uri(@"/img/2.png", UriKind.Relative));
Vlad
  • 115
  • 7