2016-07-21 40 views
0
<Image x:Name="pageImg" Margin="-19,-1,37,19" Source="/img/1.png" Stretch="Uniform" /> 

Images屬性也設置爲Build Action = Resource和複製Output Directory = Cope if newer崩潰關於更改圖片來源財產

當按鈕獲得點擊應用程序崩潰:

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

但是當我通過C:\Users\myuser\Desktop\2.png代替/img/2.png它工作得很好。

爲什麼會發生這種情況?

+1

可能重複的[在後面的代碼更改圖像源 - Wpf](http://stackoverflow.com/questions/3787137/change-image-source-in-code-behind-wpf) –

+0

@ J.H。感謝它很好地工作。 – Vlad

回答

0

這解決了我的問題:

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

的圖像資源文件(Build Action設置爲Resource)應由Resource File Pack URI加載:

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

這是沒有必要把它複製到輸出目錄。