Search code examples
c#wpfxaml

Button IsEnabled binding not working properly


Button.IsEnabled doesn't work properly.

I have debugged the code and the setter for the property was hit with the "true" value. But the button is still disabled.

View.xaml:

<StackPanel Grid.Row="2" Margin="0,20,0,0" >
        <Button Name="ButtonOk" Content="OK" Margin="0,0,4,0" IsEnabled="{Binding SomethingIsValid}"  Command="{Binding CommandOk}" />
        <Button Name="ButtonCancel" Content="Cancel" Margin="0,0,4,0" IsCancel="True" /
</StackPanel>

View.xaml.cs:

...
public View(ViewModel viewModel)
{
    this.InitializeComponent();

    this.viewModel = viewModel;
    this.DataContext = viewModel;            
}

ViewModel:

public bool SomethingIsValid
{
   get
   {
      return somethingIsValid;
   }
   set
   {
      this.somethingIsValid= value;
      this.RaisePropertyChanged(() => this.SomethingIsValid);
   }
}

#region IDataErrorInfo
public string this[string columnName]
{
   get
   {
      this.SomethingIsValid= false;

      if ("SomeName" == columnName)
      {
         if (string.IsNullOrEmpty(this.Status))
         {
            return "Please bla bla..";
         }
      }

      this.SomethingIsValid = true;
      return string.Empty;
   }
}

public string Error
{
   get
   {
      return string.Empty;
   }
}
#endregion

public ICommand CommandOk
{
   get
   {
      if (this.commandOk == null)
      {
         this.commandOk = new RelayCommand(this.CommandOkAktion, () => this.SomethingIsValid );
      }

      return this.commandOk;
   }
}

Solution

  • If you are using a command, it's not a good idea to separately bind the IsEnabled property of the button. Instead you should provide the correct value in the "CanExecute" of the command. This will enable the button as well.