简体   繁体   English

WPF绑定未更新

[英]WPF Binding not being updated

On my View model, I have the following property: 在我的View模型上,我具有以下属性:

public Visibility IsModelBusy { get; set; }

I have a long processing task that does: 我有一个很长的处理任务,它可以:

private void DoSomething(object obj)
{
    IsModelBusy = Visibility.Visible;
    OnPropertyChanged("IsModelBusy"); 
    DoHeavyWork();
    IsModelBusy = Visibility.Collapsed;
    OnPropertyChanged("IsModelBusy");
}

I have a UI element that is bound to IsModelBusy : 我有一个绑定到IsModelBusy的UI元素:

<Border Visibility="{Binding IsModelBusy, UpdateSourceTrigger=PropertyChanged}">
...
</Border>

PROBLEM My Border never gets visible and the main window hangs while the heavy task is ongoing (I can't run this in a background thread) I tried wrapping the property changed call in an action passed to a Dispatcher with no luck, the problem still persists. 问题我的边框从不可见,并且在执行繁重的任务时主窗口挂起(我无法在后台线程中运行此窗口)我尝试将属性更改后的调用包装在传递给分派器的操作中,但是运气不佳坚持。

Now if I do this: 现在,如果我这样做:

private void DoSomething(object obj)
{
    IsModelBusy = Visibility.Visible;
    OnPropertyChanged("IsModelBusy"); 
    MessageBox.Show("What the...");  <=========
    DoHeavyWork();
    IsModelBusy = Visibility.Collapsed;
    OnPropertyChanged("IsModelBusy");
}

With the introduction of the MessageBox , the UI seems to process the property changed events and update correctly. 随着MessageBox的引入,UI似乎可以处理属性更改的事件并正确更新。

QUESTION Without using background tasks, how can I force the UI to process the PropertyChanged events? 问题在不使用后台任务的情况下,如何强制UI处理PropertyChanged事件?

You're blocking the UI thread with your DoHeavyWork() . 您正在使用DoHeavyWork()阻止UI线程。

The Dispatcher cannot process any other operations (such as refreshing the UI) because it's busy executing your code. Dispatcher无法处理任何其他操作(例如刷新UI),因为它正在忙于执行代码。

Put that in a background thread. 将其放在后台线程中。

After playing around with this a lot, I finally found the answers to my questions: 经过大量的研究,我终于找到了我的问题的答案:

With the introduction of the MessageBox, the UI seems to process the property changed events and update correctly. 随着MessageBox的引入,UI似乎可以处理属性更改的事件并正确更新。

The message box forces the application to process its message queue, hence processing the property changed events and updating the UI. 消息框强制应用程序处理其消息队列,从而处理属性更改的事件并更新UI。

Without using background tasks, how can I force the UI to process the PropertyChanged events? 在不使用后台任务的情况下,如何强制UI处理PropertyChanged事件?

There is no way around this - I kept the message box solution to force the UI to process all events 无法解决此问题-我保留了消息框解决方案来强制UI处理所有事件

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

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