2009-09-02 62 views
1

我知道這是一個簡單的問題,但我無法弄清楚或在任何地方找到答案。我只是試圖在運行時使用C#在WPF中更改圖像源。每當代碼運行時,它只會刪除1.gif,並有一個空白的白框,而不是顯示2.gif。提前致謝。wpf更改圖片源

XAML:

<Image x:Name="img" Height="150" Margin="142,20,138,0" VerticalAlignment="Top"> 
     <Image.Source> 
      <BitmapImage UriSource="C:\Users\John\1.gif" /> 
     </Image.Source> 
</Image> 

C#:

string sUri = @"C:\Users\John\2.gif"; 
Uri src = new Uri(sUri, UriKind.RelativeOrAbsolute); 
BitmapImage bmp = new BitmapImage(src); 
img.Source = bmp; 
+0

'高度'設置,但'寬度'伸展以適應新的'圖像'? – Yogesh 2009-11-16 06:02:08

回答

1

您需要初始化BitmapImage。 正確的代碼會是這樣的:

BitmapImage bmp = new BitmapImage(src); 
bmp.BeginInit(); 
bmp.EndInit(); 

這應該讓您的圖像。

+0

此代碼生成InvalidOperationException「不能多次設置初始化狀態」。爲了我。只有在使用默認構造函數並稍後設置UriSource屬性時,才需要Begin/EndInit? – simonc 2011-12-21 09:57:42

+0

從您的評論看來,您的代碼看起來像是調用了BeginInit()兩次,而第二次調用它時會得到該異常。 – 2011-12-21 17:58:26

+0

同意BeginInit()被調用兩次。我認爲你的代碼片段不正確 - 在使用帶有Uri的BitmapImage ctor時,對BeginInit()和EndInit()的調用看起來沒有必要。 – simonc 2011-12-22 11:03:28

0

明顯的問題第一:你確定圖像2.gif確實存在,並且該BitmapImage的不爲空,當你設置它作爲img的來源?