jeudi 24 mai 2018

How Can I binding two commands to WPF button?

I am using WPF with MVVM pattern. I have a button and I have two commands. Furthermore I have a checkbox. And I want to bind different command to the button, depending on the checkbox ischecked or not.

For example If I click to my button It shows a message box and if I check the checkbox and I click to my button It shows a new window or something else..

I have a solution for this (I'm going to explain from high, but I think there will be exist better solution:

My ViewModel:

ICommand command1 {get; set;}
ICommand command2 {get; set;} 
ICommand commandSelector { get
{ 
  if(checkbox)
  {
     return command1;
  }else
  {
     return command2;
  }
}
private set {} }

My XAML:

<Button Label="DO" Command="{Binding commandSelector}"/>

Aucun commentaire:

Enregistrer un commentaire