MVVM模式中,BaseViewModel 的 IsBusy 属性的作用

MVVM模式中,BaseViewModel 的 IsBusy 属性的作用

在MVVM模式中,BaseViewModelIsBusy 属性主要用于管理ViewModel的异步操作状态,确保界面与后台任务的协调。以下是其核心用途和实现细节:


1. 核心作用

  • 防止重复操作

    当异步任务(如网络请求、数据库查询)执行时,将 IsBusy 设为 true,禁用按钮或控件,避免用户重复触发。

  • UI状态反馈

    在界面显示加载动画(如旋转图标、进度条),提示用户操作正在进行中。

  • 统一状态管理

    作为基类属性,所有继承的ViewModel均可复用,减少重复代码。


2. 典型使用场景

csharp 复制代码
// 在 BaseViewModel 中定义
public class BaseViewModel : INotifyPropertyChanged 
{
    private bool _isBusy;
    public bool IsBusy 
    {
        get => _isBusy;
        set 
        {
            _isBusy = value;
            OnPropertyChanged();
            // 触发命令可执行性更新(如按钮禁用)
            OnPropertyChanged(nameof(IsNotBusy)); 
        }
    }
    
    // 方便绑定反向逻辑(如按钮的 IsEnabled)
    public bool IsNotBusy => !IsBusy;

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName] string name = null) 
        => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
  • 绑定到界面控件

    xml 复制代码
    <Button Text="加载数据" 
            Command="{Binding LoadDataCommand}" 
            IsEnabled="{Binding IsNotBusy}"/>
    <ActivityIndicator IsVisible="{Binding IsBusy}" IsRunning="True"/>
  • 异步操作中的状态管理

    csharp 复制代码
    public class UserViewModel : BaseViewModel 
    {
        public ICommand LoadDataCommand => new Command(async () => 
        {
            if (IsBusy) return; // 防止重复执行
    
            IsBusy = true;
            try 
            {
                await LoadDataAsync(); // 异步任务
            }
            finally 
            {
                IsBusy = false; // 确保状态重置
            }
        });
    }

3. 高级优化

  • 计数器模式

    处理多个并发任务时,使用计数器代替布尔值:

    csharp 复制代码
    private int _busyCounter;
    public bool IsBusy 
    {
        get => _busyCounter > 0;
        set 
        {
            _busyCounter = Math.Max(0, value ? _busyCounter + 1 : _busyCounter - 1);
            OnPropertyChanged();
        }
    }
  • 附加状态信息

    扩展 BusyMessage 属性,提供更详细的提示:

    csharp 复制代码
    private string _busyMessage;
    public string BusyMessage 
    {
        get => _busyMessage;
        set 
        {
            _busyMessage = value;
            OnPropertyChanged();
        }
    }
    
    // 使用时:
    IsBusy = true;
    BusyMessage = "正在加载用户数据...";

4. 注意事项

  • 线程安全

    异步操作可能在其他线程修改 IsBusy,需确保通过 DispatcherMainThread.BeginInvokeOnMainThread(Xamarin)更新UI属性。

  • 异常处理

    try/catch/finally 中确保 IsBusy 被正确重置,避免任务异常后界面"卡死"。


通过 IsBusy,MVVM模式实现了业务逻辑与UI状态的解耦,提升代码可维护性,同时增强用户体验。

相关推荐
longxiaozhang63 小时前
C#运算符重载:让对象也能使用“加减乘除”
开发语言·c#
花落人散处4 小时前
C# 核心编程知识点总结:网络编程、委托与事件、异步编程与LINQ
c#
fl1768316 小时前
基于C#WPF实现的内存加速球清理类似360加速球内存清理
开发语言·c#·wpf
CoderIsArt8 小时前
OPC UA 完整介绍、官网、C# 简单使用
开发语言·c#
界面开发小八哥9 小时前
界面控件DevExpress XAF v26.1新版亮点——AI Agent Skills
ai·c#·跨平台·devexpress·ui开发·xaf
csdn_aspnet9 小时前
C# 高效便利的处理数据
开发语言·windows·c#
淡海水9 小时前
03-02-线性-List-T-动态数组布局-扩容与操作成本
数据结构·windows·c#·list·编译·clr·机器码
csdn_aspnet19 小时前
C# 在逗号分割的字符串中判断是否包含指定字符
c#·正则·linq·string·regex·contains
宝桥南山20 小时前
Blazor Web Assembly - 体验一下Authentication State从Server共享给Client
microsoft·微软·c#·asp.net·.net·.netcore
淡海水1 天前
02-06-历史-托管GC机制-垃圾回收如何影响数据结构选择
c#·编译·gc·机器码