【发布时间】:2019-08-01 13:27:10
【问题描述】:
我有一个带有一列的网格来显示图像(成功/失败的,两个单独的图像),我在 for 循环中执行一个 api,并根据我必须显示图像的状态(成功/失败,两个单独的图像) .我看到图像在执行后一次全部显示,但在执行期间却没有。
我推荐了 - How to load image to WPF in runtime?,但仍然无法正常工作。
public class DisplayImage
{
public static void DisplayImages(Image imgDisplay, HttpResponseMessage response)
{
BitmapImage image = new BitmapImage();
image.BeginInit();
if (response.IsSuccessStatusCode)
{
image.UriSource = new Uri(System.IO.Path.Combine(path, @"Image\Green_1.png"));
}
else
{
image.UriSource = new Uri(System.IO.Path.Combine(path, @"Image\Red.png"));
}
image.EndInit();
imgDisplay.Source = image;
imgDisplay.Refresh()
}
}
public static class ExtensionMethods
{
private static Action EmptyDelegate = delegate () { };
public static void Refresh(this UIElement uiElement)
{
uiElement.Dispatcher.Invoke(DispatcherPriority.Render, EmptyDelegate);
}
}
我希望图像在运行时显示,而不是在执行后显示。
【问题讨论】:
-
如果这应该在 UI 线程中循环运行,有一个非常简单的解决方案。发出异步网络请求,例如
HttpClient.GetAsync() -
此外,如果您有可变数量的图像,您应该考虑在 ItemTemplate 中使用带有 Image 元素的 ItemsControl,参见例如this answer 了解如何在 ItemsControl 中异步加载图像。
-
@Clemens:这与
t duplicate, its 与我已经在帖子中发布的其他线程相同,它s just that it isnt working. Also am using doing 'client.PostAsync'. I have added images in the grid without source and I将在运行时设置源。我只是希望它们在执行时显示。 -
现在已修复。我已经更新了我的答案。
-
您可能错过了问题中的一个重要细节。似乎您在 UI 线程以外的线程中运行循环。请注意,异步调用不需要这样做。