【问题标题】:WPF: Display images during execution [duplicate]WPF:在执行期间显示图像[重复]
【发布时间】: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 线程以外的线程中运行循环。请注意,异步调用不需要这样做。

标签: c# wpf image


【解决方案1】:

这可能是由于工作阻止了 UI 线程更新...

请注意,我认为您可以在 BackgroundWorker 中完成工作并使用 Dispatcher.Invoke 调用来更新 UI 线程。

【讨论】:

  • 是的!当我调用调度程序时它起作用了。更新了我的代码。
猜你喜欢
  • 1970-01-01
  • 2015-01-15
  • 2014-04-25
  • 1970-01-01
  • 1970-01-01
  • 2015-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多