Hello,
Welcome to our Microsoft Q&A platform!
Is TypedContext.IsRefreshing = true;
a static value? If so, please do not use this way to change the loading operation.
I use the official demo. Here is running screenshot. It is running normally.
You can Add a new method like DoRefresh
method. Keep the IsRefreshing
property, but achieve the IsRefreshing
property with INotifyPropertyChanged
interface, here is code about MainPageViewModel.cs
.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;
namespace App110
{
public class Item
{
public string Name { get; set; }
public Color Color { get; set; }
}
public class MainPageViewModel : INotifyPropertyChanged
{
const int RefreshDuration = 2;
int itemNumber = 1;
readonly Random random;
bool isRefreshing;
public bool IsRefreshing
{
get { return isRefreshing; }
set
{
isRefreshing = value;
OnPropertyChanged();
}
}
public ObservableCollection<Item> Items { get; private set; }
public ICommand RefreshCommand => new Command(async () => await DoRefresh());
public MainPageViewModel()
{
random = new Random();
Items = new ObservableCollection<Item>();
}
void AddItems()
{
for (int i = 0; i < 3; i++)
{
Items.Add(new Item
{
Color = Color.FromRgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255)),
Name = $"Item {itemNumber++}"
});
}
}
public async void RefreshItemsAtFirstTimeAsync()
{
IsRefreshing = true;
}
public async Task DoRefresh()
{
IsRefreshing = true;
//add your loading code
await Task.Delay(TimeSpan.FromSeconds(RefreshDuration));
AddItems();
IsRefreshing = false;
}
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
}
Then add class of bindingContext in the background code. You can execute the DoRefresh()
method directly in OnAppearing
method.
public partial class MainPage : ContentPage
{
private bool _hasRefreshedFirstTime;
MainPageViewModel mainPageViewModel;
public MainPage()
{
_hasRefreshedFirstTime = false;
mainPageViewModel =new MainPageViewModel();
BindingContext = mainPageViewModel;
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
if (!_hasRefreshedFirstTime)
{
Console.WriteLine("===============================OnAppearing=====================");
mainPageViewModel.RefreshItemsAtFirstTimeAsync();
_hasRefreshedFirstTime = true;
}
}
}
Best Regards,
Leon Lu
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.