1

I have an application which contain below code in its MainWindow.xaml to show the spinning modal using FontAwesome icon:

<Grid Visibility="{Binding SpinningModalVisibility}">
        <StackPanel>
            <fa:ImageAwesome Icon="Spinner" Spin="True" SpinDuration="5"/>
        </StackPanel>
    </Grid>

and in ViewModel, I will call

SpinningModalVisibility = Visibility.Visible;
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, (Action)(() =>
{
   //MyAction
}));
SpinningModalVisibility = Visibility.Hidden;

but for some reason, my icon is not spinning, and the modal does not behave correctly; sometime it show, sometime does not. Did I do something wrong here?

chinh nguyen van
  • 729
  • 2
  • 7
  • 18
  • first of all, Visibility.Visible must not be in your viewmodel; you must use a boolean and a converter....then what is in the stackpanel ? - typo ? – GCamel Apr 11 '17 at 12:34
  • Hi @GCamel, you are correct, I just post the simplify version of my code to make it simple. I edited the question, does you have any idea what I did wrong? – chinh nguyen van Apr 11 '17 at 12:39
  • SpinningModalVisibility is a property that send the IPropertyChanged...add this code, pls - also this code Application.Current.Dispatcher.Invoke(...must not be in your viewmodel if related to the view... – GCamel Apr 11 '17 at 12:56
  • SpinDuration is your problem ! it start from the load of the grid...not from the visibility change..! test with 10000000 – GCamel Apr 11 '17 at 12:57
  • you 'd better bind Spin="{Binding IsLoading}" to your view model – GCamel Apr 11 '17 at 12:58
  • Hi @GCamel, I used Prism MVVM and have: public Visibility SpinningModalVisibility { get { return _spinningModalVisibility; } set { SetProperty(ref _spinningModalVisibility, value); } } to refresh my UI – chinh nguyen van Apr 11 '17 at 13:23

2 Answers2

2

You should perform the action on a background thread. The UI thread cannot both display the spinner and run your code at the same time:

SpinningModalVisibility = Visibility.Visible;
Task.Factory.StartNew(()=> 
{
    //YourAction();
}).ContinueWith(Task => 
{
    SpinningModalVisibility = Visibility.Hidden;
}, System.Threading.CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
mm8
  • 163,881
  • 10
  • 57
  • 88
-1

SpinDuration=5 is your problem !

it start from the load of the usercontrol/grid...not from the visibility change..! test with bigger value

GCamel
  • 612
  • 4
  • 8
  • thank but this does not solve my issue, I used @mm8 code and it worked fine for me – chinh nguyen van Apr 11 '17 at 14:18
  • why not....it is true that your action code can freeze the gui; but you are doing it wrong : your spin control is always running (means having a timer in back; but display nothing) and Visibility must not be in the viewmodel – GCamel Apr 11 '17 at 14:37