I have a button that does some processing and I need to disable it before the process starts and enable it after the process completes. I need to accomplish this in mvvm pattern.
MainWindow.xaml
<Window x:Class="ButtonCommandBindingMVVM.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ButtonCommandBindingMVVM"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<local:ViewModel x:Key="vm"/>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="40"/>
<RowDefinition Height="40"/>
<RowDefinition Height="40"/>
<RowDefinition Height="*"/>
<RowDefinition Height="40"/>
</Grid.RowDefinitions>
<Button Grid.Row="1"
x:Name="Button1"
Width="100"
Height="27"
Content="Say Hello"
Command="{Binding Button1_ClickCommand, Source={StaticResource vm}}"
/>
<Button Grid.Row="2"
x:Name="Button2"
Width="100"
Height="27"
Content="Say Welcome"
Command="{Binding Button2_ClickCommand, Source={StaticResource vm}}"
/>
</Grid>
Command.cs This is a relay command class.
class Command : ICommand
{
Action<object> ExecuteMethod;
Func<object, bool> CanExecuteMethod;
public Command(Action<object> ExecuteMethod, Func<object, bool> CanExecuteMethod)
{
this.ExecuteMethod = ExecuteMethod;
this.CanExecuteMethod = CanExecuteMethod;
}
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
ExecuteMethod(parameter);
}
public event EventHandler CanExecuteChanged;
}
ViewModel.cs
public class ViewModel
{
public ICommand Button1_ClickCommand { get; set; }
public ICommand Button2_ClickCommand { get; set; }
public ViewModel()
{
Button1_ClickCommand = new Command(ExecuteMethodButton1_ClickCommand, CanExecuteMethodButton1_ClickCommand);
Button2_ClickCommand = new Command(ExecuteMethodButton2_ClickCommand, CanExecuteMethodButton2_ClickCommand);
}
private bool CanExecuteMethodButton1_ClickCommand(object parameter)
{
return true;
}
private void ExecuteMethodButton1_ClickCommand(object parameter)
{
await Task.Run(() =>
{
Thread.Sleep(5000);
});
MessageBox.Show("Hello");
}
private bool CanExecuteMethodButton2_ClickCommand(object parameter)
{
return true;
}
private void ExecuteMethodButton2_ClickCommand(object parameter)
{
MessageBox.Show("Welcome");
}
}
Disable the Button1 and enable it after the thread sleeps for 5 secs.