This is a mirror of official site: http://jasper-net.blogspot.com/

Implementing a non-bindable view correctly using MVVM

| Sunday, July 24, 2011
When consulting lots of other people about MVVM, I noticed that most people understand the basic concepts fairly easily. However, as soon as it becomes a little bit more complex, users immediately break the pattern and start making strange “solutions” to their problems.
The wrong “solution”

On of these problems is keeping the MVVM pattern in tact when a view does not support bindings. People don’t know how to handle the stuff, and basically come up with the following “solution” (it’s a real-world solution I’ve seen, but I’ve simplified it a bit and took the part where UI elements are used inside the view-model):

public class MainPageViewModel : ViewModelBase
{

public MainPageViewModel()
{
Navigate = new Command(OnNavigateCommand);
}

public ICommand Navigate { get; private set; }

private void OnNavigateCommand(string request)
{

FrameworkElement screenControl = GetScreenControl(request);

if (screenControl == null)
{

screenControl = CreateScreenControl(request);

DeskTopContent.Children.Add(screenControl);

ObservableCollection<TaskBarItem> taskBarItemsList = (ObservableCollection<TaskBarItem>)TaskBarItemsSource.Source;

TaskBarItem item = new TaskBarItem(screenControl, request);
...
...


If you think the solution above is good, please keep reading (you actually need it).

When I see such code, I always ask two simple questions:

  •     What is the best argument for MVVM? (they probably answer: loosely coupled design and testability)
  •     How are you going to unit test the view model above? (they probably answer: not)
Exactly, the code above cannot be unit tested because it is actually just a code-behind instead of a view model (thus the developer decided to break the MVVM pattern for whatever reason he thought was acceptable). If you think this is valid MVVM, then stop calling it a view model and call it by its name: code-behind file.
The right solution

Sometimes, when using controls that do not support MVVM bindings, you want to implement something specific, but don’t break the pattern. An excellent example of this is to use the Image control as a button. There are other solutions such as the EventToCommand behavior to solve this specific case, but this example should be easy to understand for everyone. A different example (which is a bit more complex) is for example a GridView that returns IEnumerable<GridRow> instead of a model in the ItemsSource property of the grid. However, using this as an example would make it all a bit more complex than needed.

Read more: Geert van Horrik
QR: Implementing-a-non-bindable-view-correctly-using-MVVM.aspx

Posted via email from Jasper-net

0 comments: