Search code examples
wpfloadingwaitindicator

WPF loading indicator and two buttons


enter image description here HI, i need a simple thing i need two buttons , Start ,End when pressing start loading indicator appears , when pressing End it should stop thanks in advance


Solution

  • You can use ICommand-pattern , And below is a very naive example of what you need to do (hope it helps):

    Your XAML - This is how you bind your buttons using the ICommand from your ViewModel:

    <StackPanel>
        <local:YourCustomBusyIndicator IsBusy="{Binding IsBusy}"/>
        <Button Content="Start" Command="{Binding StartCmd}"/>
        <Button Content="End" Command="{Binding EndCmd}"/>
    </StackPanel>
    

    You ViewModel Code:

    public class YourViewModel : INotifyPropertyChanged
    {
        private bool _isBusy;
        public bool IsBusy
        {
            get { return _isBusy; }
            set
            {
                _isBusy = value;
                OnPropertyChanged();
            }
        }
    
        public RoutedCommand StartCmd { get; }
        public RoutedCommand EndCmd { get; }
    
        public YourViewModel()
        {
            StartCmd = new RoutedCommand(() => IsBusy = true);
            EndCmd = new RoutedCommand(() => IsBusy = false);
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    
    
    //Simple implementation of ICommand
    public class RoutedCommand :ICommand
    {
        private readonly Action _onExecute;
    
        public RoutedCommand(Action onExecute)
        {
            _onExecute = onExecute;
        }
        public bool CanExecute(object parameter)
        {
            return true;
        }
    
        public void Execute(object parameter)
        {
            _onExecute();
        }
    
        public event EventHandler CanExecuteChanged;
    }
    

    Also the more standard way for the RoutedCommand will be also to pass a Func which returns a boolean as predicate to invoke on CanExecute