How to Bind a Command to a CheckBox
Solution 1
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.
Solution 2
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
}
}
Solution 3
This is a simple situation:
- Bind the CheckBox.IsChecked to a boolean value in your ViewModel.
- In your viewmodel, subscribe to the property changed event and watch for the boolean value to change.
Done.
Jon
Updated on June 30, 2022Comments
-
Jon almost 2 years
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
-
Jan Kratochvil about 12 yearswhat is the cmd namespace, isn't it from the MVVM Light toolkit?
-
Jan Kratochvil about 12 yearsThanks for the clarification. The thing is, not everybody is using MVVM Light (I prefer Prism) so calling it "the only preferred way" is a bit strong :-)
-
Manvinder about 12 yearsHi Orchestraor, i like your answer, kindly clear my on couple of things.You said, i need to bind my property to a Dependency property, so first i have to create a dependency property in my VM? and do i need to set the Content="Refresh" property or it could do without refreshing it?
-
Dror about 12 yearsHi Manav, Yes you would have to create a property just like I specified in the code. I call it a dependency property because it raises the NotifyPropertChanged event. that's why your ViewModel must implement the INotifyPropertChanged interface. You don't need to set any other property besides the "IsChecked" property, I only added them because they existed in Jon's question.
-
Scott almost 10 yearsSome examples of how to do this without MVVM Light can be found here.