2009-09-02 68 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的来源?