Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing MVVM in WPF without using System.Windows.Input.ICommand

Tags:

mvvm

wpf

I'm trying to implement a WPF application using MVVM (Model-View-ViewModel) pattern and I'd like to have the View part in a separate assembly (an EXE) from the Model and ViewModel parts (a DLL).

The twist here is to keep the Model/ViewModel assembly clear of any WPF dependency. The reason for this is I'd like to reuse it from executables with different (non-WPF) UI techs, for example WinForms or GTK# under Mono.

By default, this can't be done, because ViewModel exposes one or more ICommands. But the ICommand type is defined in the System.Windows.Input namespace, which belongs to the WPF!

So, is there a way to satisfy the WPF binding mechanism without using ICommand?

Thanks!

like image 554
aoven Avatar asked Feb 02 '09 14:02

aoven


People also ask

How do you implement ICommand in MVVM?

Create a folder named Model and a class named Person. Implement INotifyPropertyChanged and override the PropertyChanged event. Define two properties, Name and Address. Create a folder named ViewModel and a class named PersonViewModel.

Can you Execute in WPF?

Commands in WPF are created by implementing the ICommand interface. ICommand exposes two methods, Execute, and CanExecute, and an event, CanExecuteChanged. Execute performs the actions that are associated with the command. CanExecute determines whether the command can execute on the current command target.

What is RelayCommand WPF?

The RelayCommand and RelayCommand<T> are ICommand implementations that can expose a method or delegate to the view. These types act as a way to bind commands between the viewmodel and UI elements.


1 Answers

You should be able to define a single WPF custom routed command in your wpf layer and a single command handler class. All your WPF classes can bind to this one command with appropriate parameters.

The handler class can then translate the command to your own custom command interface that you define yourself in your ViewModel layer and is independent of WPF.

The simplest example would be a wrapper to a void delegate with an Execute method.

All you different GUI layers simply need to translate from their native command types to your custom command types in one location.

like image 183
morechilli Avatar answered Oct 03 '22 18:10

morechilli