ViewModel

Example:

View Model PNG0.png

Presented with a model I got from a colleague, that incidentally helps out as a Hockey referee when he is not coding, I wanted to create a ViewModel for the use-case “Set up new Hockey game”.

Image 11 GAME.png

The Game class has a state machine: Image 3 GAME.png

I took a piece of paper and drew the UI I wanted to achieve:

Image 4 GAME.png

Now I know what the requirements are on the ViewModel since I can see from the drawing what data the ViewModel needs to hold.

Then I created this ViewModel that I named GameSetup:

Image 5.png

Notice that it is just a series of named OCL expressions. Some expressions are nested to list other definitions like Home_PickList which states that if the game has a picked game type, then we know what teams can be chosen – namely those teams that are associated with that game type.

I created some test data so that the UI can show something. My first attempt was to manually code a WPF UI and bind the values to the ViewModel:

The UI looks like this:

GAME UI.png

This has a minimal amount of fashionably acceptable styling. The good thing is that you can hand it to any WPF-savvy designer in the world – the data and rules are safe in the ViewModel.

It already shows some of the good effects of separating UI from logic.

  1. The PickLists for Home and Visitor are filtered based on the type of game.
  2. The Picklist for the Home team filters away the Visitor team if set (and vice versa).
  3. The Start Game button is enabled only after both home and visitor are set.
  4. The End Game button is disabled until the game has started.

These are some examples of business logic that would have easily ended up in the UI if we did not have a good place to define it.

This page was edited 127 days ago on 01/11/2024. What links here