2

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 my button, it shows a message box;

if I check the checkbox and click my button, it shows a new window or something else..

I have a solution for this, but I think there can be 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}"/>
ASh
  • 34,632
  • 9
  • 60
  • 82
Xsayar
  • 75
  • 1
  • 11
  • 1
    Possible duplicate of [Binding commands to ToggleButton Checked and Unchecked events](https://stackoverflow.com/questions/25778802/binding-commands-to-togglebutton-checked-and-unchecked-events) – Jordy van Eijk May 24 '18 at 12:09
  • I'd simply use 2 buttons and one of many ways to have only 1 button visible at time: `Visibility` binding, data templates, template selector, style datatrigger, etc. – Sinatr May 24 '18 at 13:10

1 Answers1

12

it is possible to change Command property binding in a Trigger:

<Button Label="DO">    
    <Button.Style>        
        <Style TargetType="Button">            
            <Setter Property="Command" Value="{Binding command2}"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsChecked, ElementName=someCheckBox}" Value="True">
                    <Setter Property="Command" Value="{Binding command1}"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>        
    </Button.Style>    
</Button>

but probably it is better to have a single command, and perform different action based on check state in a command handler:

ICommand commandSelector { get; set; }

private void commandSelectorExecute(object o)
{
    if (checkbox)
       DoSmth();
    else 
       DoSmthElse();
}
ASh
  • 34,632
  • 9
  • 60
  • 82