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

.NET MAUI中ActivityIndicator绑定值变更后不显示问题

问题解决:ActivityIndicator未随属性变化显示

核心原因

你的ViewModel没有实现INotifyPropertyChanged接口,当ShowActivityIndicator属性值改变时,无法通知UI同步更新,导致ActivityIndicator不会显示。另外,当前的按钮命令是普通方法,不符合ICommand的绑定要求,且同步执行HTTP请求会阻塞UI线程,进一步导致Indicator无法正常渲染。

修复步骤

1. 让ViewModel实现INotifyPropertyChanged接口

给ViewModel添加接口实现,用于属性变化通知:

using System.ComponentModel;
using System.Runtime.CompilerServices;

public class YourViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

2. 修改ShowActivityIndicator属性,触发更新通知

将自动属性改为带字段的属性,在set方法里触发通知:

private bool _showActivityIndicator;
public bool ShowActivityIndicator
{
    get => _showActivityIndicator;
    set
    {
        if (_showActivityIndicator != value)
        {
            _showActivityIndicator = value;
            OnPropertyChanged();
        }
    }
}

3. 将按钮命令改为ICommand并异步执行HTTP请求

使用ICommand实现命令绑定,同时用异步方法避免阻塞UI线程:

using System.Windows.Input;
using System.Threading.Tasks;

// 声明命令属性
public ICommand UploadSurveyCommand { get; }

public YourViewModel()
{
    // 初始化命令,关联异步执行方法
    UploadSurveyCommand = new RelayCommand(async () => await UploadSurveyAsync());
}

// 异步执行上传逻辑
private async Task UploadSurveyAsync()
{
    ShowActivityIndicator = true;
    try
    {
        // 替换为你的HTTP请求代码
        // await HttpClient.PostAsync("your-api-url", content);
    }
    finally
    {
        // 请求完成后关闭Indicator
        ShowActivityIndicator = false;
    }
}

// 简单的RelayCommand实现(无第三方库时可用)
public class RelayCommand : ICommand
{
    private readonly Action _execute;
    private readonly Func<bool> _canExecute;

    public event EventHandler CanExecuteChanged;

    public RelayCommand(Action execute, Func<bool> canExecute = null)
    {
        _execute = execute ?? throw new ArgumentNullException(nameof(execute));
        _canExecute = canExecute;
    }

    public bool CanExecute(object parameter) => _canExecute?.Invoke() ?? true;

    public void Execute(object parameter) => _execute();

    public void RaiseCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}

4. 确认页面BindingContext已正确设置

确保页面的BindingContext指向你的ViewModel实例,比如在页面构造函数中:

public YourPage()
{
    InitializeComponent();
    BindingContext = new YourViewModel();
}

完成以上修改后,点击按钮时ShowActivityIndicator的变化会实时通知UI,ActivityIndicator将正常显示,异步请求也不会阻塞UI线程,保证Indicator能正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 03:33:16