Disable WPF buttons during longer running process, the MVVM way

后端 未结 4 457
遇见更好的自我
遇见更好的自我 2020-12-16 13:12

I have a WPF/MVVM app, which consists of one window with a few buttons.
Each of the buttons triggers a call to an external device (an USB missile launcher), which takes

4条回答
  •  遥遥无期
    2020-12-16 13:50

    Because you run CallExternalDevice() on the main thread, the main thread won't have time to update any UI until that job is done, which is why the buttons remain enabled. You could start your long-running operation in a separate thread, and you should see that the buttons are disabled as expected:

    private void CallExternalDevice(object obj)
    {
        this.disableGui = true;
    
        ThreadStart work = () =>
        {
            // simulate call to external device (USB missile launcher),
            // which takes a few seconds and pauses the app
            Thread.Sleep(3000);
    
            this.disableGui = false;
            Application.Current.Dispatcher.BeginInvoke(new Action(() => CommandManager.InvalidateRequerySuggested()));
        };
        new Thread(work).Start();
    }
    

提交回复
热议问题