3

I am trying to add multiple commands to my very first MVVM program. But the way I am adding them here feels wrong to me. I want to prevent as much duplication as possible, can I make a kind of parent command that I can easily modify for example?

internal class AddTimerBarCommand : ICommand
{
    public AddTimerBarCommand(MainViewModel viewModel)
    {
        _MainViewModel = viewModel;
    }

    private MainViewModel _MainViewModel;
    public event EventHandler CanExecuteChanged;

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public void Execute(object parameter)
    {
        _MainViewModel.AddTimerBar();
    }
}

internal class RmvTimerBarCommand : ICommand
{
    public RmvTimerBarCommand(MainViewModel viewModel)
    {
        _MainViewModel = viewModel;
    }

    private MainViewModel _MainViewModel;
    public event EventHandler CanExecuteChanged;

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public void Execute(object parameter)
    {
        _MainViewModel.RmvTimerBar();
    }
Unhek
  • 93
  • 1
  • 9

2 Answers2

7

Are you looking for a base class to reduce code duplication?

If so, this might work for you:

internal abstract class TimerBarCommandBase : ICommand
{
    public TimerBarCommandBase(MainViewModel viewModel)
    {
        _MainViewModel = viewModel;
    }

    protected MainViewModel _MainViewModel;
    public event EventHandler CanExecuteChanged;

    public bool CanExecute(object parameter) { return true; }

    public abstract void Execute(object parameter);
}

internal class AddTimerBarCommand : TimerBarCommandBase
{
    public AddTimerBarCommand(MainViewModel viewModel) : base(viewModel) { }

    public override void Execute(object parameter)
    {
        _MainViewModel.AddTimerBar();
    }
}

internal class RmvTimerBarCommand : TimerBarCommandBase
{
    public RmvTimerBarCommand(MainViewModel viewModel) : base(viewModel) { }

    public override void Execute(object parameter)
    {
        _MainViewModel.RmvTimerBar();
    }
}
Enigmativity
  • 113,464
  • 11
  • 89
  • 172
  • very interesting, I did not know I could base constructors on parent constructors. I will play with this – Unhek Oct 11 '15 at 02:45
0

The answer given by Enigmativity is good since you asked for a way to optimize your code.

But, in MVVM, when it comes to using ICommand, normally we use a RelayCommand that is implemented in the MVVM Framework used for the project.

Here is a tutorial written by Laurent Bugnion the developer of MVVM Light. Using this, you won't have to create a new class every time you want to bind a command and therefore will "prevent as much duplication as possible".

Joel Bourbonnais
  • 2,618
  • 3
  • 27
  • 44