简体   繁体   English

关于在WPF中刷新UI的困惑

[英]Confusion about Refreshing the UI in WPF

I have heard that this refreshes the UI but why so? 我听说这会刷新UI,但为什么会这样呢? Dispatcher invokes this empty action and thats it there is no call InvalidateMeasure() which would trigger the UI to re-measure and re-arrange and re-render inside the action. Dispatcher调用此空操作,即没有调用InvalidateMeasure() ,这将触发UI重新测量并重新排列并在操作内重新呈现。 Where is here the measure and arrange process to update/refresh the UI? 这里测量和安排update/refresh UI的过程在哪里?

private static Action EmptyDelegate = delegate() { };

public static void Refresh(UIElement uiElement)
{
   uiElement.Dispatcher.Invoke(DispatcherPriority.Render, EmptyDelegate);
}

Any help? 有帮助吗?

EDITED: I want to know the details why is UI rendered. EDITED:我想知道为什么UI呈现的细节。 Answers like well that triggers ui update are not helping me any further guys. well that triggers ui update答案well that triggers ui update没有帮助我任何进一步的人。

Microsoft recommends a slighty different way of doing what your code does using PushFrame . Microsoft建议使用PushFrame执行代码执行操作的略微不同方式。

The code has nothing to do with rendering. 代码与渲染无关。 What it does is similar to the DoEvents method known from VB6 and WinForms. 它的作用类似于VB6和WinForms中已知的DoEvents方法。 DoEvents halts the program while pumping the Windows message queue and handling the messages in the queue. DoEvents在泵送Windows消息队列和处理队列中的消息时暂停程序。 This includes any rendering messages such as WM_PAINT and WM_NCPAINT . 这包括任何渲染消息,如WM_PAINTWM_NCPAINT

The code instructs the Dispatcher to halt the current thread and pump its queue and handle all messages that have a priority of DispatcherPriority.Render or higher. 代码指示Dispatcher暂停当前线程并抽取其队列并处理优先级为DispatcherPriority.Render或更高的所有消息。 If there are any pending rendering messages in the queue, for example if InvalidateRect has been called somewhere by the framework, these messages will be handled and the UI will be re-rendered. 如果队列中有任何挂起的呈现消息,例如,如果框架在某处调用了InvalidateRect ,则将处理这些消息并重新呈现UI。

DoEvents has always been considered a code smell because it bypasses the message queue. DoEvents一直被认为是代码气味,因为它绕过了消息队列。 If you want a responsive user interface you should use worker threads instead. 如果您需要响应式用户界面,则应使用工作线程。

This can be used to force WPF to update the UI because of the priority of the invocation. 由于调用的优先级,这可用于强制WPF更新UI。 Since this invoke uses the Dispatcher synchronously, any tasks that are already queued with an equal or higher priority than DispatcherPriority.Render will be run before running the delegate you provided. 由于该调用使用调度同步,已经与相同或更高的优先级比队列中的任何任务DispatcherPriority.Render会运行您提供的委托之前运行。

Here is the list of potential values of DispatcherPriority , and it explains the order tasks are run by the dispatcher. 以下是DispatcherPriority的潜在值列表,它解释了调度程序运行的订单任务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM