gpt4 book ai didi

wpf - 从任务更新 ViewModel 属性

转载 作者:行者123 更新时间:2023-12-03 10:26:28 26 4
gpt4 key购买 nike

我正在使用 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,但我的代码可以正常工作。是否有我遗漏的东西并且可能会导致偶发错误,或者在幕后是否有一些魔法来处理同步?

最佳答案

这将取决于您如何实现 INotifyPropertyChanged。实现应将所有 UI 更新委托(delegate)给适当的调度程序。

示例实现:

public void RaisePropertyChanged([CallerMemberName]string name) {
Application.Current.Dispatcher.Invoke(() => {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}, System.Windows.Threading.DispatcherPriority.Background);
}

同时清理一下任务开始:

编辑:删除了不必要的 bool 返回值,并设置 ConfigureAwait 以在任务完成时离开 UI 线程。

public async void Start()
{
await Task.Run(() => example()).ConfigureAwait(false);
}

private async Task example()
{
for (int i = 0; i < 100; i++)
{
Progress = i + 1; // this triggers PropertChanged-Event and leads to the update of the UI
await Task.Delay(20);
}
}

关于wpf - 从任务更新 ViewModel 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42116253/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com