wpf更改图像源

发布于 2024-08-03 14:09:46 字数 567 浏览 3 评论 0原文

我知道这是一个简单的问题,但我无法弄清楚或在任何地方找到答案。我只是尝试使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

鱼忆七猫命九 2024-08-10 14:09:46

您需要初始化 BitmapImage。
正确的代码应该是这样的:

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

这应该会得到你的图像。

You need to initialize the BitmapImage.
The correct code would be something like:

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

That should get you your image.

昔日梦未散 2024-08-10 14:09:46

首先是明显的问题:您确定图像 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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文