This project has moved and is read-only. For the latest updates, please go here.

BusyIndicator with MVVM: binding IsBusy to a property in the ViewModel

Sep 13, 2011 at 8:08 PM

Hi,

I am trying to have the BusyIndicator shown when a background operation is performed, and hidden when it's done.

The property is defined in the ViewModel class, and used as follows:

 

//...
        private bool isBusy;
        public bool IsBusy
        {
            get
            {
                return isBusy;
            }
            set
            {
                if (value != isBusy)
                {
                    isBusy = value;
                    RaisePropertyChanged("IsBusy");
                }
            }
        }
//...

        private void ExecuteActionInBackground(Action workerMethod)
        {
            IsBusy = true;

            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += delegate(object sender, DoWorkEventArgs e)
            {
                workerMethod();
            };
            worker.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e)
            {
                IsBusy = false;
            };
            worker.RunWorkerAsync();
        }

 

In View's XAML I have:

<Grid x:Name="LayoutRoot">
       <extToolkit:BusyIndicator IsBusy="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}},
                                                                      Path=DataContext.IsBusy}" >
            <!-- content -->
       </extToolkit:BusyIndicator>
</Grid>

 

The problem is that the BusyIndicator doesn't get shown.

I stepped through the code in debugger - everything seems to be working just fine.

I even attached a simple Converter to the binding - and actually see the values changed between True and False!

What am I missing?

Please help.

 

Thanks,

Alex

Sep 13, 2011 at 8:46 PM

Everything looks correct.  I would check your Output window and make sure you don't have any data binding errors.  Depending on how you have set your DataContext, you could just set your binding to IsBusy="{Binding IsBusy}"

Sep 13, 2011 at 11:06 PM

I suspect the problem may be with threading: the IsBusy is updated in the callback invoked when another window is closed.

I tried to enclose the callback's code into Dispatcher.CurrentDispatcher.Invoke... To no avail. Any ideas?

Sep 14, 2011 at 7:13 AM

I don't believe that is the issue as long at the ExecuteActionInBackground method is being called on the UI thread.  The background code may be executing faster than the BusyIndicator can show.  I would remove the workerMethod call and replace it with a loop with a thread.Sleep in it to see if that works.

May 20, 2013 at 2:41 PM
I think, you are not properly telling the DataContext in xaml.