MVVM Part 6: InteractingViewModel / IUserInteracter

How can ViewModels become nearly independant from their concrete view but still keep the control over it?
IUserInteracter can be an answer.

Note: This posting is part of a series. See MVVM-Library for other parts and download.

As the last part of this series is more than one month ago, I really have to publish this now 🙂 So please excuse some undocumented parts, unfinished classes and not working code in the MVVM-Library. I will correct it later.

Where did we breake off?

In the last part we were able to abstract the user interface using the IUserInterface interface. At the end, we could use this IUserInterface to show IShowables. However, we do not have any Showables yet – so we can not really use our IUserInterface.

What this part is about

Now we want to connect the IUserInterface and our ViewModels.

Let’s start!

Read the rest of this entry »

Advertisements

[WPF] Hide the “Window Buttons” (minimize, restore and close) and the icon of a window

No “Red-X”? Then I can’t close the window! How to achieve this reaction in WPF applications.

Even if it is not always the user friendliest way, there are situation in which you do no want the user to close a window using the “red X” in the upper right corner of a window’s non client area (sometimes only called “Close Button” 😉 ).

In most cases this behavior is expected from Dialogs which usually do not have “Minimize” and “Maximize” buttons. So it’s a common practice to hide the whole so called “System Menu”, “Control Box” or “System Bar”.

Windows Forms

It’s quite easy to do so in Windows Forms: Simply set the ControlBox property to false:

Read the rest of this entry »

MVVM Part 5: IUserInterface

This posting shows how to abstract the user interface in a WPF MVVM application. We will see how the IUserInterface interface helps us reducing the coupeling between the ViewModel classes and UserControls / Windows.

Note: This posting is part of a series. See MVVM-Library for other parts and download.

It has been some time ago since I published the last part “Commanding”. I hope you didn’t loose the interest in my blog meanwhile 😉

Today, we will concentrate on another, very important aspect: Letting the ViewModels open new Views (in fact we are only preparing for that step).

Bad solution

As the ViewModels should not know about their concrete views, it would be very bad to write code like that in a ViewModel class:

Window window = new Window();
window.DataContext = new FooViewModel();
window.Child = new FooView();

window.Show();

Read the rest of this entry »

Posted in My interpretation of MVVM, WPF. Tags: , , , , . Comments Off on MVVM Part 5: IUserInterface

MVVM Part 4: Commanding

Note: This posting is part of a series. See MVVM-Library for other parts and download.

Commanding is a very important topic in MVVM applications as it represents – together with Data Binding – the only mode of interaction between ViewModel and View.

Predefined Commands

In WPF there are three predefined commands:

Class Diagram: Predefined Commands in WPF

However, there is one problem: While ICommand encapsulates a “real” command that knows what to do itself, RoutedCommand and RoutedUICommand are dependant on the logical tree. Routing through the element tree, they look for a command binding which then invokes a method containing the actual implementation / logic.

So they are used totally different. Routed(UI)Commands are normally supplied as static fields or properties. ApplicationCommands is one example: The command declared there come with no logic; the addressee has to provide it.

Josh Smith’s Solution

Almost one year ago, Josh Smith published the article Using RoutedCommands with a ViewModel in WPF on Code Project (I recommend you reading through it).

In short: He introduced an easy way how to use RoutedCommands from within the ViewModel without connecting it to strong to the UI. He was able to do so by writing his own CommandBinding class. Unlike than many other people he did not write classes implementing ICommand and made them available in the ViewModel.

At this point: Many thanks to him for this really great article!!!

Why do I mention him and his article here? Well, my commanding solution is based on some of his ideas. Although I rewrote lots of his code you’ll still find some of the original code in my project.

My solution

The main players are the same – the members changed a bit:

Class diagram: My Solution

Note: VS seems to have problems with displaying delegates in class diagrams. The correct signature for CommandSink.RegisterCommand is “CommandSink.RegisterCommand(RoutedCommand command, Func<object, CommandState> getCommandStateCallback, Action<object> executeCallback)”.

CommandState

There was one main thing, I changed: Instead of providing a method CanExecute, I introduced GetCommandState which returns a new object, a CommandState.

What is a CommandState?

A command state gives information about the state a ViewModel has affecting the way of executing a command.

That may include:

  • If the command can be executed
  • Why a command can not be executed
  • What the execution of the command will change
  • Any warnings a user should notice before doing something

As the first point is essential, CommandState includes CanExecute which indicates exactly this. There are also two (non-abstract) subclasses ExecutableCommandState and NotExecutableCommandState which allow you using CommandStates without writing subclasses.

However, the other points can only be covered with custom inheritors of CommandState.

Why using CommandStates?

CommandStates help you implementing a very important factor for usability: dynamic feedback.

The UI informs the user, what will happen if he clicks on button a. In opposite to static tooltips which have to handle multiple cases, you build your tooltips dynamically and integrate the status information you get from a CommandState. You even can show why an action can not be done.

How should a CommandState look like?

In order to allow different UIs for your ViewModel classes, you should use almost no formatted data. That means: Work with enumerations, bools, … and collections of them.

As CommandState is derived from ViewModelBase, there are nearly unlimited possibilities to present the data to the user. (Note: A later posting will introduce some kind of factory for views that makes this process much easier again).

The sample project does it wrong: It uses one CommandState for everything that is only different in its message. Why am I not using multiple CommandStates then? Well, it’s not only the “ViewFactory” I did not introduce yet. I had to decide: Introduce them all in this article or writing that workaround. I chose the second. You’ll see later, why you should use them in this case 🙂

CommandSinkCommand

I already mentioned that my solution relies on “implementation-less” RoutedCommands.

In some cases, however, it isn’t possible to use them (especially when the command would never reach its target).

In order to be prepared to situations like these, CommandSinkCommand represents a routing-independent ICommand – you don’t have to write your code twice.

CommandingViewModel

CommandingViewModel implements ICommandSink (and of course ViewModelBase). Because of that it is able to be the target of routed commands.

How to declare and register your own commands?

I have written two snippets for that (“command” and “regCommand”). The sample project shows how commands are correctly declared and registered.

CommandStateExtension

CommandStateExtension simplifies evaluating the state of a command connected to a specific control. As the sample project contains an example for that, too, I won’t explain its usage further.

Sample Project

Screenshot of teh sample application Take a look at the screenshot on the left:

My sample project today is a simple counter where the buttons communicate with the ViewModel using RoutedCommands.

In additions there are labels indicating the “status” of each command.

Download it from MVVM-Library.

Posted in My interpretation of MVVM, WPF. Tags: , , , , , , . Comments Off on MVVM Part 4: Commanding

MVVM Part 3: ViewModelBase

Note: This posting is part of a series. See MVVM-Library for other parts and download.

Class Diagram of ViewModelBase It’s time for our first real “ViewModel” class: ViewModelBase.

As a ViewModel is – I already said before – databound to the UI it inherits NotifyKnownPropertyChanged to provide base support for Data Binding.

Data Binding to a WPF UI brings up another problem: The PropertyChanged event may only be raised in the UI thread.

In order to handle forbidden accesses from other threads and to make “Invoke”-scenarios possible, ViewModelBase remembers the dispatcher of the thread which created it. The methods for this purpose should be self-explanatory.

Note: ViewModel hides NotifyKnownPropertyChanged.OnPropertyChanged in order to perform a (debug-only) check ensuring it was called from the right thread. I thought a while if it would be better to make NotifyKnownPropertyChanged.OnPropertyChanged virtual and implement an auto-invoke solution.  As ViewModel classes are not thread safe (in general), however, but may be able to deal with callbacks (etc.) executing in other threads, this approach is ok in my opinion. Derived classes must not call OnPropertyChanged from another thread – if they do though there will only be an error when using the debug build.

Today, I won’t post an sample project because ViewModelBase makes only sense if it is inherited. You can download the updated ViewModel project (without the sample for the last part) here: MVVM-Library.

Posted in My interpretation of MVVM, WPF. Tags: , , , , , . Comments Off on MVVM Part 3: ViewModelBase

MVVM Part 2: Property Changing

Note: This posting is part of a series. See MVVM-Library for other parts and download.

Remember that ViewModels are databound to the View?

How are they bound?

You might know that the binding engine in WPF relies on INotifyPropertyChanged for that:

The INotifyPropertyChanged interface is used to notify clients, typically binding clients, that a property value has changed.

For example, consider a Person object with a property called FirstName. To provide generic property-change notification, the Person type implements the INotifyPropertyChanged interface and raises a PropertyChanged event when FirstName is changed.

Property Names as strings…

PropertyChanged expects an instance of PropertyChangedEventArgs which provides a property PropertyName containing the name of the property that has changed as a string.

Thinking about my recently published posting Ban string literals from your code! you might be able to comprehend why I not really like that way: You can easily misspell the property name.

My solution

Class Diagram

Class Diagram

The classes

Property

The class Property represents a property (quite logical, isn’t it ;-)) with all its properties: The type that declares it, its name, its returning type and a callback that returns it value for an passed object.

It is the core of this project part.

Properties are immutable objects that are created via the static Factory-Method Create. You can either pass a PropertyInfo object or a Func<T, object> (speaking strictly a Expression<Func<T, object>>) which returns the value of the property. (Example later in this posting).

KnownPropertyChangedEventArgs

KnownPropertyChangedEventArgs is an EventArgs class that inherits PropertyChangedEventArgs and adds the property Property returning a Property 🙂 object.

INotifyKnowPropertyChanged

INotifyKnowPropertyChanged implements INotifyPropertyChanged and hides its PropertyChanged event. Instead it declares an event with the same name but of type EventHandler<KnownPropertyChangedEventArgs>.

So INotifyKnowPropertyChanged also informs about property changes. However, it identifies the changed property not via a simple string but with an object of the described Property class.

NotifyKnownPropertyChanged

NotifyKnownPropertyChanged provides a default implementation of the INotifyKnowPropertyChanged interface.

It maximizes comfort by providing two different methods:

  • OnPropertyChanged: Derived classes will call this method in order to notify about property changes.
  • NotifyPropertyChanged: This method will be called whenever a property changes (respectively when OnPropertyChanged is called). You can override it in order to be notified about property changes.

Sample project

The sample project today is quite small: It’s a simple console application to show how to use those classes. You can find it at MVVM-Library.

Code Snippet

I created a small snippet that helps declaring properties using this way of property change-tracking.

Your opinion

What do you think?

Any bugs / issues / suggestions?

Looking forward to your comments!

Posted in My interpretation of MVVM, WPF. Tags: , , , , , , . Comments Off on MVVM Part 2: Property Changing

MVVM Part 1: Overview

There have already been quite a few articles, HOW-TOs and tutorials to the Model-View-ViewModel (MVVM) architecture.

One of the best is WPF Apps With The Model-View-ViewModel in my opinion.

However, I have different or advanced solutions for some problems. So I’ll start a series with an unknown number of parts about this topic.

Still, I explicitly recommend reading the others, too. Only this will help you to find your interpretation of MMVM.

What is MVVM?

MVVM is a pattern that helps to separate the behavior of an User Interface from its design.

Why doing so?

There are several reasons for that:

  • Separation: UI and logic are separated for changing them without affecting the other one
  • Testing: Plain UIs can not be tested easily. ViewModels can.
  • Support of different views: You want to create multiple UIs for an application? That’s much easier
  • Ease of the use of WPF Controls: Ever tried to fill a Treeview in WPF without MVVM? It’s quite uncomfortable.
  • Taking advantage of WPF-Features like Data Templates, Data Binding and dynamic Control creation

The three players

The Model

What?

In short, the Model is the “real application”. It represents all the business logic.

Do not see the Model as something passive or as something that contains no logic!

Where are its limits?

The Model shouldn’t contain any logic to directly interact with the user. This shouldn’t be any new information.

This includes displaying of Windows / Forms / MessageBoxes but also formatting data. That’s none of their business!

Checklist

A little “checklist” for a good Model (of course, there may be exceptions here); arbitrary order:

  • Did I use no class contained in System.Windows (and inferior namespaces)? Thus, I need no reference to PresentationFramework.dll, System.Windows.Forms, PresentationCore, …?
  • Is it neither laid out for Windows Forms, nor WPF? Could I use everything in a Console Application theoretically?
  • Am I using content that needs to be translated? It’s only OK for messages that won’t displayed to the user. (Exceptions – if you prefer using localized ones – and Logfiles can be exceptions)
  • Is there no need of additional logic concerning working with my Model-classes? That means: Every kind of manipulation the application itself does to its data (e.g. functions like “Load the latest stocks from our homepage” or “Do an automatic cleanup and delete all Customers that made no order during the last year”) should be implemented here.
  • Does my Model perform validation?
  • Did I implement code to fetch objects from my data store and save it there? Is this procedure abstracted by my Model? Did I also abstract the specific queries so the user of my classes doesn’t need to know about the structure of my database?
  • Did I use events when requiring feedback from the user?

The ViewModel

Well, what is the ViewModel then?

According to my definition it is a layer which is databound to the view and prepares the model in order to be displayed by it. It does so by providing a kind of proxy classes. Thereby it simplifies complicated situations by changing the structure of the model.

What does it do?

As already said in the definition: Its main task is simplifying and restructuring data in a form that can’t be visualized directly by the view. Everything is supplied in a bindable way by implementing INotifyPropertyChanged.

Every action you can perform (this also includes object creation) is exposed as a command.

There are three “base” types of patterns: Selecting one or more items, Changing a property, Invoking a method.

Where are its limits?

The ViewModel should not know about the concrete view. Only the structure of a view is considered when creating it. By saying “structure” I neither mean the layout nor the real “looking”. “Structure” describes what a user can actually do – something like “There is a possibility to change the name of a person.” or “Items can be deleted, added, and reordered here”.

In my opinion, formatting (of primitive values – e.g. setting the number of decimal points or combining two or more properties to a new one) is also not a part of the ViewModel.

One important thing, a ViewModel should never do: Do not use classes from “System.Windows”. That means: No MessageBox.Show, no creation of Windows, …

Checklist
  • Is the ViewModel “easy” to use?
  • Does it track property changes and report them via INotifyPropertyChanged?
  • Do all properties either return another ViewModel, a primitive data type or a collection of one of these?
  • Does it not contain any String.Concats, String.Formats, … in order to combine two or more properties to a new one?
  • Are there commands for every action you can do with the ViewModel?
  • Is it independent of the current UI?
  • Did I use no classes declared in “PresentationFramework.dll” (which includes all controls)?
  • Is every action exposed as a command?

The View

What?

The view is the “real UI” or simply “that thing you can really see”. For each ViewModel there is exactly one UserControl representing it.

This UserControl is assembled out of existing controls (of course there can be user generated controls – however, these controls should be independent). It has no code-behind and only consist of XAML-Code. Data Templates, Data Binding, Styles and Resources are used to a great extent.

All formatting, arrangement and visualizing of data is done here.

Where are its limits?

Although the View displays everything, it’s designed more passive than active. It only invokes commands, and changes databound properties. It will never change something by code.

Therefore, it contains no program logic.

Checklist
  • Does the View only use the ViewModel (and not the Model) classes?
  • Is the View free of logic that affects more than the UI itself?
  • Is there exactly one UserControl per each ViewModel class?
DotNetKicks Image