Implementing RaiseCanExecuteChanged()
Command Class:
public class CommandBase : ICommand
{
Action _TargetExecuteMethod;
Func<bool> _TargetCanExecuteMethod;
public CommandBase(Action executeMethod)
{
_TargetExecuteMethod = executeMethod;
}
public CommandBase(Action executeMethod, Func<bool> canExecuteMethod)
{
_TargetExecuteMethod = executeMethod;
_TargetCanExecuteMethod = canExecuteMethod;
}
public void RaiseCanExecuteChanged()
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
public event EventHandler CanExecuteChanged
public bool CanExecute(object parameter)
{
if (_TargetCanExecuteMethod != null)
{
return _TargetCanExecuteMethod();
}
if (_TargetExecuteMethod != null)
{
return true;
}
return false;
}
public void Execute(object parameter)
{
if (_TargetExecuteMethod != null)
{
_TargetExecuteMethod();
}
}
}
View:
<TextBox Grid.Row="3" Text="{Binding TextValue, UpdateSourceTrigger=PropertyChanged }"/>
<Button Content="DoSomething" Command="{Binding DoSomething}" />
ViewModel class:
public class MyclassViewModel
{
private string textValue;
public String TextValue
{
get {
return textValue;
}
set {
textValue = value;
DoSomething.RaiseCanExecuteChanged();
}
}
public CommandBase DoSomething { get; set; }
public MyclassViewModel() //Constructor
{
DoSomething = new CommandBase(OnDoSomething, CanDoSomething);
}
private bool CanDoSomething()
{
if (TextValue?.Length > 5)
{
return true;
}
return false;
}
private void OnDoSomething()
{
//Do Something
}
}