display Hourglass when application is busy

前端 未结 9 1639
说谎
说谎 2020-11-28 03:01

For a view constructed using WPF, I want to change the mouse cursor to a hourglass when the application is busy and nonresponsive.

One solution is to add



        
9条回答
  •  眼角桃花
    2020-11-28 03:38

    I used the answers here to build something that worked better for me. The problem is that when the using block in Carlo's answer finishes, the UI might actually still be busy databinding. There might be lazy-loaded data or events firing as a result of what was done in the block. In my case it sometimes took several seconds from the waitcursor disappeared until the UI was actually ready. I solved it by creating a helper method that sets the waitcursor and also takes care of setting up a timer that will automatically set the cursor back when the UI is ready. I can't be sure that this design will work in all cases, but it worked for me:

        /// 
        ///   Contains helper methods for UI, so far just one for showing a waitcursor
        /// 
        public static class UiServices
        {
    
        /// 
        ///   A value indicating whether the UI is currently busy
        /// 
        private static bool IsBusy;
    
        /// 
        /// Sets the busystate as busy.
        /// 
        public static void SetBusyState()
        {
            SetBusyState(true);
        }
    
        /// 
        /// Sets the busystate to busy or not busy.
        /// 
        /// if set to true the application is now busy.
            private static void SetBusyState(bool busy)
            {
                if (busy != IsBusy)
                {
                    IsBusy = busy;
                    Mouse.OverrideCursor = busy ? Cursors.Wait : null;
    
                    if (IsBusy)
                    {
                        new DispatcherTimer(TimeSpan.FromSeconds(0), DispatcherPriority.ApplicationIdle, dispatcherTimer_Tick, Application.Current.Dispatcher);
                    }
                }
            }
    
            /// 
            /// Handles the Tick event of the dispatcherTimer control.
            /// 
            /// The source of the event.
            /// The  instance containing the event data.
            private static void dispatcherTimer_Tick(object sender, EventArgs e)
            {
                    var dispatcherTimer = sender as DispatcherTimer;
                    if (dispatcherTimer != null)
                    {
                        SetBusyState(false);
                        dispatcherTimer.Stop();
                    }
            }
        }
    

提交回复
热议问题