DCSIMG
MVVM for Silverlight – what is it about? - Ran Wahle's blog

Ran Wahle's blog

MVVM for Silverlight – what is it about?

MVVM for Silverlight – what is it about?

I recently had the pleasure of having Elad Katz as a consultant for the customer SilverLight
I work for on
Sela’s behalf. Elad’s job was to lead us migrating a “regular”
Silverlight project to MVVM .

This post is the first in a series discussing MVVM and it’s application in
Silverlight. In here I’ll discuss about what MVVM is all about and what are
it’s advantages.

What is MVVM ?

MVVM is a design pattern aimed mainly to separate (and decouple)
the graphic design  from it’s data and behavior (It is based on MVC
and MVP but differs, leveraging the XAML advantages).

MVVM stands for Model View  ViewModel:

Model – The data context or the data access representing the context (The same as MVC)

View – The graphic design. Views are XAML files mainly user controls.

View-Model – The “Model of the View” : Acts as the view’s data context. The View-Model
has also the logical behavior, mostly everything you’ll find on a user control’s code behind
should be in a View-Model

Relations:

View “knows” the View-Model as it’s data context. The view’s child control has data
bindings to various properties of the View-Model

View-Model calls services and performs client logics. This means that in most cases,
you shouldn’t write anything on the Views code-behind.
   

This separation gives as, along with code readability (once you get used to the pattern)
is the ability to test UI behavior, and with proper mocking, you can see how the controls
and pages can look like with some actual data.

Moreover, because of this separation, you may change your view’s appearance , layout etc.
without touching it’s behavior. Try without MVVM to replace type of controls, remove control
and so on. ’m sure that every change of this kind causes changes in various places on your
code-behind.

You can read detailed information about it Here and Here, however, in order to best
understand the concept, let’s see how View and View-Model work together.

 

How does it work

I’m sure you’re all familiar with this line of XAML:

   <TextBlock Text="{Binding Path=TimePicked, Mode=OneWay}"></TextBlock>
For those of you who aren’t : This binds a property to a control (Textblock
in this case ) but have we thought to have  a DataContext as a class that’s has
all what we have in our code-behind?

Well, that’s actually the main idea behind MVVM .The view’s control’s properties
are bound to the View-Model properties.

So, Let’s build a simple View-Model  demo:

1. Because View-Model properties are bound to the view’s inner controls, it should
    implement the
INotifyPropertyChanged interface.

2. Every set to the property has to invoke the PropertyChanged event on every
    set, meaning that a property should look like that.

   private DateTime timePicked = DateTime.MinValue;
        public DateTime TimePicked
        {
            get
            {
                return timePicked;
            }
            set
            {
                timePicked = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged(this,
new PropertyChangedEventArgs("TimePicked"));
                }

            }
        }
  That’s how we make sure that property recent value is always shown on it’s bound
control
.
3. Now, let’s change the TimePicked property. In here we do it every second
This piece of code should do so.
  DispatcherTimer timer;
        public TimeViewModel()
        {
            timer = new DispatcherTimer();
            timer.Interval = new TimeSpan(0, 0, 1);
            timer.Tick += Timer_Elapsed;//
            timer.Start();
          
        }

        private void Timer_Elapsed(object sender, EventArgs e)
        {
            TimePicked = DateTime.Now;
          
        }
In here, we’ve set a timer on our View-Model constructor. you can see that it is a private member
of the View-Model, no other class (including views) should know it.
4. Let’s attach the View-Model to the view. All we need to do is set our DataContext property.
    You may use ViewModelLocator In here I’ve put the ViewModel in my application resources
and set the DataContext property in my user control (view) like that:
    (App.Xaml)
<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
            x:Class="MVVMDemo.App"
            xmlns:vm="clr-namespace:MVVMDemo.ViewModels"
            >
    <Application.Resources>
        <vm:TimeViewModel x:Key="TimeViewModel"></vm:TimeViewModel>
    </Application.Resources
>
</
Application
>
(User control attribute on root node)
DataContext="{StaticResource TimeViewModel}"

 

Now, all we have to do is compile the application, then we can see the TextBlock
switches values as time goes by.You might notice that it does so even on design
time, think how great it is for the graphic designer who can see how the application
would look like, with actual data in it.

 

Summary

I’ve talked a little bit about what MVVM is, demonstrated it by a (very small) demo
and showed how a DataContext can control logic behavior of view, and do so|
without knowing the  view itself. Main advantages are the ability to change the
view without touching the ViewModel and of course test the ViewModel
and overcome the difficulties of UI-testing.

 

You can download the full source from here

 

kick it on DotNetKicks.com

Comments

MVVM ??? Using commands - Ran Wahle's blog said:

Pingback from  MVVM ??? Using commands - Ran Wahle&#39;s blog

# March 3, 2011 10:35 AM

Ran Wahle's blog said:

One of the things I’ve cherished the most about XAML related technologies development was the ability to completely decouple behavior and UI using MVVM. I didn’t know about any possibility to implement the same pattern on HTML &amp; Javascript based applications

# November 20, 2011 4:48 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: