Button is not getting enable on Command Enable, doEnable method. Click method is disabling button. Button IsEnabled is Bind with ViewModel public property IsEnable, which is setting true on doEnable. Kindly advise what is wrong in below Code
XAML:
<Button Content="{Binding DataText}" Height="30" Width="80" Command="{Binding Enable}" Click="ButtonBase_OnClick" IsEnabled="{Binding IsEnable}" ></Button>
Window2.cs:
public partial class Window2 : Window
{
public Window2()
{
InitializeComponent();
DataContext = new ButtonEnableViewModel();
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
if(sender is Button btn)
btn.IsEnabled = false;
}
}
ButtonEnableViewModel.cs
class ButtonEnableViewModel : INotifyPropertyChanged
{
public ButtonEnableViewModel()
{
IsEnable = true;
DataText = "Click Here";
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChange(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
private RelayCommand _enableCmd;
public RelayCommand Enable => _enableCmd ?? (_enableCmd = new RelayCommand(doEnable));
public bool IsEnable { get; set; }
public string DataText { get; set; }
protected void doEnable(object obj)
{
IsEnable = true;
DataText = "Clicked";
OnPropertyChange(nameof(IsEnable));
OnPropertyChange(nameof(DataText));
}
}
ButtonBase_OnClicksetIsEnabledproperty tofalse, but yourEnablecommand set same property totrue. What are you trying to do?CanExecutemethod of the command to disable theButton. Most implementations of theICommandinterface accepts aPredicate<object>that you can use to tell the command when to enable the command/button.