Jon
Jon

Reputation: 1727

How to Bind a Command to a CheckBox

I'm trying to bind the checkbox checkchange event to a command - MVVM Why doesn't this work? or do anything while the same works on button?

<CheckBox x:Name="radRefresh" IsChecked="{BindingREADY, Mode=TwoWay}" Command="{Binding Refresh_Command}" Content=" Refresh "  Margin="10,25,0,0"  />

<Button Command="{Binding Refresh_Command}" />

thanks

Upvotes: 3

Views: 15045

Answers (4)

Manvinder
Manvinder

Reputation: 4591

This will work...

<i:Interaction.Triggers> <i:EventTrigger EventName="Click"> <cmd:EventToCommand Command="{Binding Path=YourCommand,Mode=OneWay}" CommandParameter="{Binding IsChecked, ElementName=YourCheckBox}"></cmd:EventToCommand> </i:EventTrigger> </i:Interaction.Triggers>

where i is

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

Add namespace for cmd

    xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WPF4"

This is one of the preferred ways for MVVM if you are utilizing the MVVMLight Framework.

Upvotes: 3

myermian
myermian

Reputation: 32525

This is a simple situation:

  1. Bind the CheckBox.IsChecked to a boolean value in your ViewModel.
  2. In your viewmodel, subscribe to the property changed event and watch for the boolean value to change.

Done.

Upvotes: 2

Dror
Dror

Reputation: 2588

You don't need to bind it to an event. All you need to do is bind IsChecked to a boolean dependency property, and do whatever logic you'd like on its setter.

Like this -

<CheckBox x:Name="radRefresh" IsChecked="{Binding IsChecked, Mode=TwoWay}" Content=" Refresh "  Margin="10,25,0,0"  />

This xaml should bind you to this property on the VM

  public bool IsChecked
  {
      get
      {
          return isChecked;
      }
      set
      {
          isChecked = value;
          NotifyPropertChanged("IsChecked");

          //Add any logic you'd like here
       }
   }

Upvotes: 9

Jan Kratochvil
Jan Kratochvil

Reputation: 2327

That would be because only a handful of controls (Button, MenuItem of the top of my head) implement the functionality to directly bind commands.

If you need to bind to a control, I would recommend creating a UserControl that executes the ViewModel's command when the CheckBox's property IsChecked is changed in codebehind.

Upvotes: 0

Related Questions