mvvm pattern in c#

This is an implementation in C# of the MVVM pattern as described before.

In this implementation I use the MVVM light toolkit, and some patterns I’ve already described: inversion of control and dependecy injection.

First, lets start with the model:

    public class NoteModel : ObservableObject
    {
        private string _note;
        public string Note
        {
            get { return _note; }
            set { Set(ref _note, value); }
        }

        private bool _isFinished;
        public bool IsFinished
        {
            get { return _isFinished; }
            set { Set(ref _isFinished, value); }
        }
    }

As you can see, when assigning to a property, I use a method provided my the MVVM light library: Set(). This method assigns the new value to the property, and fires the IPropertyChanged event, if the new value differs from the old. The IPropertyChanged event allows the view to refresh automatically.

Now, lets look at the view:

<Page DataContext="{Binding MainViewModel, Source={StaticResource Locator}}">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="10" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid Grid.Row="0">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="Auto" />
            </Grid.ColumnDefinitions>
            <TextBox Text="{Binding NewNote, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
            <Button Command="{Binding AddNoteCommand}" >
                <Button.Content>
                    <SymbolIcon Symbol="Add" />
                </Button.Content>
            </Button>
        </Grid>
        <ListView ItemsSource="{Binding Notes}" />
    </Grid>
</Page>

I’ve removed all styling informations so everything is easier to understand. Take a look at DataContext: MainViewModel is a property of Locator, and this property is bound to the view. Take a look at the TextBox to see what this means: the Text property is filled with another {Binding NewNote...}, and NewNote is a property of the MainViewModel from above.

There are three types of binding in this example:

  • read binding: The ListView binds itself to the Notes property.
  • read & write in the Textbox: The Mode=TwoWay ensures, user input is written into the property automatically by XAML magic.
  • command binding: the Button binds itself to a property called AddNoteCommand, this property implements the ICommand interface. We’ll see about that.

I recommend you to take a look at this in Visual Studio, this helps you to understand all the other magic XAML stuff.

One last thing to check out: the {StaticResource Locator} part in the DataContext, you’ll find the definition the App.xaml:

<viewModels:ViewModelLocator x:Key="Locator" />

which leads to (in the Presentation project, ViewModels folder):

    public class ViewModelLocator : ViewModelLocatorBase
    {
        public ViewModelLocator()
        {
            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
            SimpleIoc.Default.Register<IPlatformInformations, PlatformInformations>();
        }
    }

and this leads to (in the View project, ViewModels folder)

    public class ViewModelLocatorBase
    {
        public ViewModelLocatorBase()
        {
            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
            SimpleIoc.Default.Register<IDataService, DataService>();
            SimpleIoc.Default.Register<MainViewModel>();
        }

        public MainViewModel MainViewModel => SimpleIoc.Default.GetInstance<MainViewModel>();
    }

Now there is the MainViewModel property!
The SimpleIoc part is an implementation of the Inversion of Control pattern, and provided by the Mvvm light library.

Now the ViewModel.
The constructor part:

    public class MainViewModel : ViewModelBase
    {
        private readonly IDataService _dataService;

        //inversion of control: SimpleIoc will contruct this object with the registered IDataService implementation
        public MainViewModel(IDataService dataService)
        {
            _dataService = dataService;

            _addNoteCommand = new RelayCommand(AddNote, () => CanAddNote);
            _deleteNoteCommand = new RelayCommand<NoteModel>(DeleteNote);

            if (IsInDesignMode)
            {
                Notes = new ObservableCollection<NoteModel>()
                {
                    new NoteModel()
                    {
                        Note = "Hello World",
                        IsFinished = false
                    }
                };
            }
            else
            {
                Initialize();
            }
        }

        private async void Initialize()
        {
            Notes = await _dataService.GetTasks();
        }

        private ObservableCollection<NoteModel> _notes;
        public ObservableCollection<NoteModel> Notes
        {
            get { return _notes; }
            set { Set(ref _notes, value); }
        }
    }

MainViewModel inherits from the ViewModelBase, a class provided by the MVVM light library. It has some nice tools integrated, for example the IsInDesignMode propery.

The ObservableCollection takes care of the necessary events firing, so the view can refresh itself if necessary.

The NewNote property is the one filled by the Textbox. Depending on the input, one can create a new note. So every time the value changes (Set returns true if the value has changed), the should reevaluate if a new note could be created.


        private string _newNote;
        public string NewNote
        {
            get { return _newNote; }
            set
            {
                if (Set(ref _newNote, value))
                    _addNoteCommand.RaiseCanExecuteChanged();
            }
        }

The commands:

        private readonly RelayCommand _addNoteCommand;
        public ICommand AddNoteCommand => _addNoteCommand;

        private bool CanAddNote => !string.IsNullOrEmpty(NewNote);

        private void AddNote()
        {
            Notes.Add(new NoteModel() { Note = NewNote });
            NewNote = "";
        }

        private readonly RelayCommand<NoteModel> _deleteNoteCommand;
        public ICommand DeleteNoteCommand => _deleteNoteCommand;

        private void DeleteNote(NoteModel model)
        {
            Notes.Remove(model);
        }

You can pass an object directly to the command, as done with the DeleteNoteCommand, with the CommandParameter property in the view.

Now start the application and play with it a little bit.
You’ll notice two things:

  • Without any code in view, the displayed items are always up to date. Even some basic animations already work
  • The logic is completely divided from the display, you may use the exact same ViewModel in an Android or iOS application

mvvm pattern

MVVM stands for Model-View-Viewmodel, a pattern used for example in applications & programs for windows.

ModelViewViewmodel

First, lets take a look at the three parts:

Model

a model is an object which stores data, and most of the time represents an object from the real world which is managed by the application. It is used to store data.

Viewmodel

Each page in your application has a Viewmodel associated with it. The Viewmodel provides all data to be displayed in the view and all commands which a user is able to execute

View

The View focuses solely on display.

Why use this pattern?

This pattern, similar to MVC, allows a loose coupling between Application Logic and View Logic. This has some numerous advantages:

  • extensibility & maintainability
  • if you have to redesign the application, you would not need to rewrite already working application logic, you only have to replace the view, and vice versa
  • easy for other developers to understand what you were doing

The full power of this pattern, and why I love it more than MVC, is shown the way it is supported in windows applications.

I’ve made an example in C#: github

I explain this example in detail here

mvc pattern in php

This is an implementation in php of the MVC pattern as described before.

First, we need to ensure all requests go to one file only, the index.php file. There we will construct our controller, and run the application. We do this by placing a correctly configured .htaccess file in the root directory of our webpage. I’ve commented out the commands, feel free to take a look.

The actual code in the index.php file is quite simple:

// (skipped code for including files)

//construct the controller
$controller = new HomeController($_SERVER["REQUEST_URI"]);
//execute the application
echo $controller->execute();

That was easy. Let’s take a look at our controller:

class HomeController {
	private $params;
	
	/**
	 * HomeController constructor.
	 *
	 * @param $params : the request URL
	 */
	public function __construct($params) {
		$this->params = $params;
	}
	
	/**
	 * execute the application
	 *
	 * @return string
	 */
	public function execute() {
		if ($this->params == "/") {
			$view = new HomeView("hallo welt!");
			return $view->renderHome();
		}
		else {
			if ($this->params == "/famoser") {
				$view = new HomeView();
				$person = new PersonModel("famoser", "01.01.1990");
				return $view->renderPerson($person);
			}
			else {
				if ($this->params == "/famoser/multiple") {
					$view = new HomeView();
					$persons = array();
					for ($i = 0; $i &amp;amp;amp;lt; 5; $i++) $persons[] = new PersonModel("famoser (" . $i . ")", "01.01.1990"); return $view->renderMultiplePersons($persons);
				}
				else {
					$view = new HomeView("not found");
					$view->addKeyValue("url", $this->params);
					return $view->renderError();
				}
			}
		}
	}
}

As you can see, the controller checks if the $params variable is a valid url. If it is, it contructs an object called the HomeView, and passes models and text to it. Then it lets the HomeView render the templates, and returns the received data.

Let take a look at a simplified HomeView (full code at github):

/**
* a simplyfied HomeView, I've removed the constructor and other for this example irrelevant code
*/
class HomeView {
	private $message;
	private $keyValues;

	public function getMessage() {
		return $this->message;
	}
	
	/**
	 * use this function to pass simple data to the view
	 */
	public function addKeyValue($key, $value) {
		$this->keyValues[$key] = $value;
	}
	
	/**
	 * retrieves values added by addKeyValue from the controller
	 */
	public function getValue($key) {
		return $this->keyValues[$key];
	}
	
	/**
	 * render the home template
	 */
	public function renderHome() {
		return $this->includeFile("index");
	}
	
	/**
	 * render the person template
	 */
	public function renderPerson(PersonModel $person) {
		$this->person = $person;
		return $this->includeFile("person");
	}

	/**
	 * render multiple persons
	 */
	public function renderMultiplePersons(array $persons) {
		$result = "";
		foreach ($persons as $person) {
			$this->person = $person;
			$result .= "

" . $this->includeFile("person") . "

";
		}
		return $result;
	}
	
	/**
	 * renders a file, writes the output it produces into a variable and returns that.
	 */
	private function includeFile($fileName) {
                //shorted
                include $filename;

	}
}

As you can see, the HomeView basically serves as a container for all data it needs to display. As the controller calls a function as renderHome, it loads a specific template and returns the rendered content to the controller.
Lastly, lets take a look at a template file:

if ($this instanceof HomeView) {
	echo $this->getMessage();
}

As I’m including the file from the HomeView, the context in this file ($this) is still the view. Now I can call the methods from the view to retrieve the data I have to render to human readable information.

What advantages has this approach?

  • reuse of templates is made easy: from one template, I can include others by calling functions provided by the view object (for example renderMultiplePersons)
  • a clear separation of view & logic: the controller does not care how the data he provides is displayed, he simply constructs the view with the appropriate data, and the view does not care where the data comes from, and just loads the appropriate templates.

mvc pattern

MVC stands for Model-View-Controller, a pattern widely used in web application development.
First, lets take a look at the three parts:

ModelViewController

Controller

For each part of your application you use a different controller. It executes a different set of instructions based on the request, manages the models, and constructs the view.

Typically, after a request is made, following steps are undertaken by the controller:

  • check if the request is valid, else return an error message
  • update data if the request wishes to do so
  • retrieve all data needed in the view
  • construct a view object, and let it render the view

Model

a model is an object which stores data, and most of the time represents an object from the real world which is managed by the application. It is the primary form of communication between your views and your controllers.

View

the view is responsible for displaying information received from the controller such as models.

Why use this pattern?

This pattern allows a loose coupling between Application Logic and View Logic. This has some numerous advantages:

  • extensibility & maintainability
  • if you have to redesign the application, you would not need to rewrite already working application logic, you only have to replace the view, and vice versa
  • easy for other developers to understand what you were doing

I’ve made an example in php: github

I explain this example in detail here

repository pattern

This pattern is an application of the separation of concerns principle. It basically separates the consumer from the supplier of data.

For the consumer of an RSS feed it is irrelevant if the feed is read out from the storage, or downloaded from the internet. This is where the Repository Pattern jumps into action; it provides a simple API for the consumer, and takes care of resolving the data from the best source available.

A small example (c#):

internal class RssRepository
{
    public List<RssItem> GetRssItems()
    {
        if (DeviceHelper.HasInternet)
        {
            return RssHelper.DownloadFeedItems();
        }
        else
        {
            return StorageHelper.RetrieveCachedFeedItems();
        }
    }
}

inversion of control

A very handy pattern for large projects. Think of it as an enhancement from the dependency injection pattern.

When using dependency injection, the caller of a class provides the implementations of the requirements.
This gets cumbersome with classes which have a lot of requirements, and large code bases where you may not even know where the implementation is, or how it is called.

Inversion Of Control to the rescue: With this pattern, the framework provides the implementations.

As the implementation is a bit more complex, I’ll only explain the concept:

  • Create a helper, which can construct classes with requirements (non-empty contructor with interfaces)
  • Register the implementations you want to use against the helper at a central place in your code
  • Retrieve all classes which have requirements over this helper

An Example in pseudo-php code:

class IoCContainer extends Singleton
{
    private $registeredInterfaces = array();
    public function register($interface, $implementation)
    {
        $this->registeredInterfaces[$interface] = $implementation;
    }

    public function construct($object)
    {
        $arguments = get_needed_arguments($object);
        //match each argument with an implementation, and construct the object
        return $instance;
    }
}

now at the start of your application you register the implementations:

IoCContainer::getInstance()->register("IProgress",new ProgressService());
class Workflow
{
    public function __construct(IProgress $progressService) { }

    public function doStuff() { }
}
IoCContainer::getInstance()->construct("Workflow")->doStuff();

Now, you do not want to write an IoCContainer yourself. Not because it is hard, but because it has been made before, and tested before. For C# I can recommend the SimpleIoC Container from the MVVMLight Package: MVVM Light (you can get it over NuGet). There are similar implementations for most other languages.

dependecy injection

This is one of my favorite patterns out there! Use this if you have a large codebase or multiple consumers of a library.

Use case: You have some code, and multiple Consumers (Webpage, Phone Application & Desktop Application) which want to use the contained Logic (so you do not copy paste the same code three times). Now you want to show progress for a long running operation in the DownloadLargeFileWorkflow. What to do:

  • You create a IProgress interface
  • Each of your Consumers implements this interface
  • You pass the instance which implements this interface to the shared code.

Ready! Now you can use the same code for all three very different consumers.

Now how to implement this?

public interface IProgress
{
    void ShowProgress();
    void HideProgress();
}

public class DownloadLargeFileWorkflow
{
    private IProgress _progress;
    pulic DownloadLargeFileWorkflow(IProgress progress)
    {
        _progress = progress;
    }

    public void Execute()
    {
        _progress.ShowProgress();
        //do long running operation
        _progress.HideProgress();
    }
}

In your consumer specific code you can now construct the DownloadLargeFileWorkflow with your specific implementation of the IProgress interface.

singleton

If you use this, only do so for logging. This pattern is widely described as an anti-pattern, don’t tell me I did not warn you: Patterns I Hate #1: SingletonSingleton (…) you’re bringing me down. Still, I do like this pattern because if its simplicity, and Dependency Injection or the Factory pattern is for small projects sometimes just overkill.

This pattern ensures there is only one instance of a class active.
This is useful for logging, where you only need one logging instance.

The implementation itself is quite simple:

php (for C# see here: github):

    
class Singleton
{
    //overwrite those two methods to "disable" them
    private function __clone() {}
    private function __construct() {}

    //our saved instances
    protected static $instances = array();

    /**
     * @return static
     */
    final public static function getInstance()
    {
        $classname = get_called_class();
        if (!isset(static::$instances[$classname])) {
            static::$instances[$classname] = new static();
        }
        return static::$instances[$classname];
    }
}

To use this pattern you simply inherit from the singleton class, and then call MyOneAndOnly::getInstance() (php) or MyOneAndOnly.Instance.HelloWorld (C#)

class MyOneAndOnly extends Singleton 
{
    public function helloWorld() { return "hello"; }
}

echo MyOneAndOnly::getInstance()->helloWorld(); //prints "hello"

Only use this pattern if your application does not depend on the data of the Singleton; you only pass data to the object, but never retrieve any. This scenario is true for a Logger, or for a Stopwatch to test the performance of your application. For any other scenario fo not use this, as it makes your code harder to understand and to test