Search code examples
xamlwindows-phone-8mvvmwindows-runtime

XAML ProgressRing doesn't stop


My problem is that ProgressRing is running all the time. I use MVVM. ProgressRing could be active only when app get new data.

I have code in VM (I updated ViewModel):

public class MainPageViewModel : ObservableCollection<AdModel>, ISupportIncrementalLoading{
    private Visibility _loaderVisibility;
    public Visibility LoaderVisibility
    {
        get { return _loaderVisibility; }
        private set
        {
            _loaderVisibility = value;

        }}
    public IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
    {
        CoreDispatcher coreDispatcher = Window.Current.Dispatcher;

        return Task.Run<LoadMoreItemsResult>(async () =>
        {
            await coreDispatcher.RunAsync(CoreDispatcherPriority.Normal,
                () =>
                {
                    this.LoaderVisibility = Visibility.Visible;
                });

            var NewAds = new ObservableCollection<AdModel>();

            do{NewAds = await LoadAds();//get data from API}
            while (NewAds == null);

            await coreDispatcher.RunAsync(CoreDispatcherPriority.Normal,
                () =>
                {
                    foreach (AdModel item in NewAds)
                    {
                        this.Add(item);
                    }
                    this.LoaderVisibility = Visibility.Collapsed;
                });

            return new LoadMoreItemsResult() { Count = count };
        }).AsAsyncOperation<LoadMoreItemsResult>();}}

Solution

  • First you need to fire the PropertyChanged event when you change the LoaderVisibility property, so that UI can be notified of the new value. See an example on how to Implement Property Change Notification.

    The LoaderVisibility property should look like this (this VM class needs to implement the INotifyPropertyChanged interface, so you have the PropertyChanged event).

    private Visibility _loaderVisibility; 
    public Visibility LoaderVisibility 
    {
        get { return _loaderVisibility; }
        set 
        {
            _loaderVisibility = value;
            OnPropertyChanged(new System.ComponentModel.PropertyChangedEventArgs("LoaderVisibility"));
        }
    }
    

    Second, do not set the ProgressRing's Visibility property from code behind, that will break the data binding you wire up in XAML.