Disable WPF buttons during longer running process, the MVVM way

后端 未结 4 459
遇见更好的自我
遇见更好的自我 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:33

    Try this:

    //Declare a new BackgroundWorker
    BackgroundWorker worker = new BackgroundWorker();
    worker.DoWork += (o, ea) =>
    {
        try
        {
            // Call your device
    
            // If ou need to interact with the main thread
           Application.Current.Dispatcher.Invoke(new Action(() => //your action));
        }
        catch (Exception exp)
        {
        }
    };
    
    //This event is raise on DoWork complete
    worker.RunWorkerCompleted += (o, ea) =>
    {
        //Work to do after the long process
        disableGui = false;
    };
    
    disableGui = true;
    //Launch you worker
    worker.RunWorkerAsync();
    

提交回复
热议问题