【发布时间】:2017-02-08 14:48:02
【问题描述】:
我正在使用 WPF 和 Caliburn.Micro 构建一个应用程序。我想从任务/线程更新 ProgressBar,我想知道正确更新 UI 需要什么:
public class DemoViewModel : PropertyChangedBase
{
private int m_Progress;
public int Progress
{
get { return m_Progress; }
set
{
if (value == m_Progress) return;
m_Progress = value;
NotifyOfPropertyChange();
NotifyOfPropertyChange(nameof(CanStart));
}
}
public bool CanStart => Progress == 0 || Progress == 100;
public void Start()
{
Task.Factory.StartNew(example);
}
private void example()
{
for (int i = 0; i < 100; i++)
{
Progress = i + 1; // this triggers PropertChanged-Event and leads to the update of the UI
Thread.Sleep(20);
}
}
}
从其他编程语言中,我知道我需要与 UI 线程同步以更新 UI,但我的代码可以正常工作。是否有什么我遗漏了并且可能导致零星错误的东西,或者是否有一些幕后的魔法可以处理同步?
【问题讨论】:
-
INPC 事件会自动编组到 UI 线程,因此您不必担心。但是...如果您每 20 毫秒更新一次 UI(Thread.Sleep(20)!!!!!!!),您将不会在 UI 中看到 jack,因为它会忙于实际更新。跨度>
标签: wpf mvvm caliburn.micro