wpf更改图像源
我知道这是一个简单的问题,但我无法弄清楚或在任何地方找到答案。我只是尝试使用 C# 在 WPF 运行时更改图像源。每当代码运行时,它只是删除 1.gif 并显示一个空白的白框,而不是显示 2.gif。提前致谢。
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;
I know this is an easy question but I can't figure it out or find the answer anywhere. I'm just trying to change the image source during runtime in WPF using C#. Whenever the code runs, it just removes 1.gif and has a blank white box, instead of displaying 2.gif. Thanks in advance.
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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要初始化 BitmapImage。
正确的代码应该是这样的:
这应该会得到你的图像。
You need to initialize the BitmapImage.
The correct code would be something like:
That should get you your image.
首先是明显的问题:您确定图像 2.gif 确实存在,并且当您将其设置为 img 源时 BitmapImage 不为 null?
Obvious questions first: you're sure that the image 2.gif really exists, and that the BitmapImage isn't null when you set it as the source of img?