PhOeNiX
PhOeNiX

Reputation: 295

MVVM restricts Code Behind?

Does using MVVM model in WPF restricts the programmer from writing code behind? Avoiding Code behind results in lot of complications but on the other hand coupling rises as an issue. So what is better?

Upvotes: 2

Views: 501

Answers (1)

Emond
Emond

Reputation: 50672

The MVVM model does NOT restrict you from writing code behind.

What it does promote is that the View should only be dependent on the ViewModel (and the ViewModel on the Model)

So if you write code behind that is actually implementing the ViewModel you are creating a dependency from the ViewModel to the View.

Code behind that ONLY does View related things is OK

The thing you are losing when using code behind is the easy (unit)testing of that code.

EDIT

A common expression in MVVM-world is "XAML only". As much as I like a short, snappy statement it tends to divert from the actual problem MVVM is trying to solve and how it tries to solve it.

As long as you stick to making the View dependent on the ViewModel and the ViewModel on the Model AND strive for (unit)testability you are on the right track.

EDIT 2

In the View handling an event should only do two things: change the View itself or notify the ViewModel using a binding that something has changed. Notifying the VIEW of a change in the ViewModel should be done by implementing INotifyPropertyChanged on the ViewModel.

In a similar way the ViewModel can respond to events in the View by binding ViewModel Commands to the View.

A WPF Button has a Command property that can be used. It is executed when the button is clicked.

If a control has no Command property or you want to execute a command when a different event is raised all you have to do is turn the event into the execution of an ICommand.

Microsoft already provided an implementation of that in the Blend SDK. From this article:

... xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity..."
<Slider
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="ValueChanged">
            <i:InvokeCommandAction Command="{Binding MyCommand}"
                                   CommandParameter="{Binding Text, ElementName=textBox}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Slider>

And a discussion about commands versus event triggers

Upvotes: 7

Related Questions