Disable WPF buttons during longer running process, the MVVM way

后端 未结 4 460
遇见更好的自我
遇见更好的自我 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条回答
  •  旧时难觅i
    2020-12-16 13:46

    I think this is a bit more elegant:

    XAML:

    
    

    C# (using async & await):

    public class MainWindowViewModel : INotifyPropertyChanged
    {
        private bool isGuiEnabled;
    
        /// 
        /// True to enable buttons, false to disable buttons.
        /// 
        public bool IsGuiEnabled 
        {
            get
            {
                return isGuiEnabled;
            }
            set
            {
                isGuiEnabled = value;
                OnPropertyChanged("IsGuiEnabled");
            }
        }
    
        public ICommand DeviceCommand
        {
            get
            {
                return new RelayCommand(this.CallExternalDevice, this.IsGuiEnabled);
            }
        }
    
        private async void CallExternalDevice(object obj)
        {
            IsGuiEnabled = false;
            try
            {
                await Task.Factory.StartNew(() => Thread.Sleep(3000));
            }
            finally
            {
                IsGuiEnabled = true; 
            }
        }
    }
    

提交回复
热议问题