How to handle Checkbox Checked / Unchecked checkbox with command in ViewModel in Silverlight?

I have a view (X.Xaml) that has some controls, including a CheckBox .

When I check the CheckBox , it should make the session True, and when I take it off, it should make the False session.

If I do this in X.Xaml.cs code, it will be easy, but I want my code to be clean.

Can I use the Command command and process it in the ViewModel side?

+4
source share
3 answers

To answer your question: yes, there is.

You need to create a Command implementation of the ICommand class:

 public class MyCommand : ICommand { Action<bool> _action; public MyCommand(Action<bool> action) { _action = action; } public bool CanExecute(object parameter) { return true; } public event System.EventHandler CanExecuteChanged; public void Execute(object parameter) { _action((bool)parameter); } } 

then in your ViewModel create a command:

 private MyCommand simpleCommand; public MyCommand SimpleCommand { get { return simpleCommand; } set { simpleCommand = value; } } public MainViewModel() { SimpleCommand = new MyCommand(new Action<bool>(DoSomething)); } public void DoSomething(bool isChecked) { //something } 

And bind the Checkbox command to it, and CommandParameter

 <CheckBox Name="checkBox1" Command="{Binding Path=SimpleCommand}" CommandParameter="{Binding ElementName=checkBox1, Path=IsChecked}" /> 

But this is a little exaggerated. You should probably create the corresponding bool property in the ViewModel, bind to it and call the required code inside the accessor.

+3
source

Why can't you just create a TwoWay binding on the IsChecked-Property to the ViewModel-Property and react to this property change?

in the ViewModel:

 private bool _IsSessionEnabled; public bool IsSessionEnabled { get { return _IsSessionEnabled; } set { if (_IsSessionEnabled != value) { _IsSessionEnabled = value; this.OnPropertyChanged(); this.switchSession(value); /* this is your session code */ } } } 

and in view:

 <CheckBox IsChecked={Binding IsSessionEnabled, Mode=TwoWay} Content="Session active" /> 

It would be even more clean to respond to property changes in your own OnPropertyChanged implementation before (or after you like) by raising an event.

+6
source

You can use the command, or you can use data binding with a change notification.
In the view, simply bind the command property to the checkbox. I just call the Changed command.

 Command={Binding Changed}" 

ViewModel

 bool session = false; RelayCommand Changed = new RelayCommand(()=>{this.session = !this.session}); 
0
source

All Articles