Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle Checkbox Checked/Unchecked event with Command in ViewModel in Silverlight?

Tags:

c#

silverlight

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

When I check the CheckBox it should make a session True and when I uncheck it, it has to make the session False.

If I do it in the X.Xaml.cs code-behind, it would be easy but I want my code to be clean.

Is there anyway to use Command and handle it in ViewModel side?

like image 890
peter prova Avatar asked Jan 21 '13 14:01

peter prova


2 Answers

To answer your question: yes, there is.

You have to create Command class implementing ICommand:

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 the command itself:

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 your Checkbox command to it, and the CommandParameter to Checkbox.IsChecked

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

But that's a bit exaggerated. You're probably better off creating respective bool property in the ViewModel, bind to it and invoke required code within the accessor.

like image 160
StaWho Avatar answered Oct 18 '22 18:10

StaWho


Why can't you simply create a TwoWay-Binding on the IsChecked-Property to a ViewModel-Property and react on that 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 the view:

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

It would be even cleaner to respond on the Property Change in your own OnPropertyChanged implementation before (or after, as you like) raising the event.

like image 32
eFloh Avatar answered Oct 18 '22 17:10

eFloh