You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FreshMVVM静态同步方法更新UI绑定进度条属性的问题求助

同步进度绑定失效解决方案

核心解决思路是使用.NET官方提供的IProgress<T>类型实现进度回调,不需要在静态同步方法中实例化ViewModel,避免绑定实例不匹配的问题。

步骤1:修改静态同步方法,增加进度回调参数

调整FirebaseCloudNight类的SynchronizeNights方法,新增IProgress<float>类型的入参,每完成一条数据同步就将当前进度通过回调抛出:

namespace iVanApp.Services {
public class FirebaseCloudNight : FirebaseCloudBaseHelper
{
    // 新增progress参数用于回调进度
    static public async Task<bool> SynchronizeNights(IProgress<float> progress = null)
    {
        // Synchronize from Cloud to DB
        int currentNight = 0;
        int numberOfNights = cloudNights.Count;
        foreach (var cloudItem in cloudNights)
        {
            try
            { 
                // 原有拉取线上DB代码保留
                currentNight ++;
                // 计算进度并回调
                if(progress != null)
                {
                    float currentProgress = (float)currentNight / numberOfNights;
                    progress.Report(currentProgress);
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        // 注意:原有代码return true写在foreach内会导致第一次循环就返回,需移到循环外
        return true;
     }
 }
}

步骤2:ViewModel中调用方法时传入回调实例

在ViewModel的GetData方法中创建Progress<float>实例,回调逻辑直接更新当前实例的CurrentProgress属性,触发绑定通知:

async Task GetData()
{
    // 创建进度回调实例,回调逻辑默认在UI线程执行,无需额外处理线程调度
    var progress = new Progress<float>(p => 
    {
        CurrentProgress = p;
    });
    bool success = await FirebaseCloudNight.SynchronizeNights(progress);                 
}

float currentProgress;
public float CurrentProgress
{
    get => currentProgress;
    set
    {
        currentProgress = value;
        RaisePropertyChanged();
    }
}

这种方案完全符合MVVM分层逻辑,服务层不需要感知ViewModel的存在,仅通过通用回调抛出进度,既实现了进度更新,也保证了服务层代码的复用性。

内容的提问来源于stack exchange,提问作者Bumbar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 16:18:05