Sunday, April 12, 2015

Introduction to MVVM for WPF using VB

If you search Amazon.com for books on WPF and MVVM you will find the pickings rather slim. If you add in a filter for Visual Basic you are left with nothing. Although many good people have published blogs and walkthroughs describing MVVM, they tend to be complex and/or full of errors and ambiguities and they are almost all in C#. I decided to buck the trend and write a series of blog entries for VB coders that takes gentle steps.

We've all been coding using techniques that are very much like MVVM for years. We understand the need for data abstraction layers and separation of the UI from the data model. The only big conceptual change we need to make is that in WPF and MVVM the UI controls the linkage to the data model rather than the other way around.

For example, we are used to writing code like this to set the content of a textbox to a value...
FirstNameTextBox.Text = "John"

With WPF we bind the text property to a FirstName property in the data context and write
Employee.FirstName = "John"

That, in my opinion, is the biggest paradigm change from Model-View-Controller to Model-View-ViewModel -- The ViewModel is now the owner of the data, not the View.

Now the big difference between regular WPF and WPF with MVVM is that the ViewModel is not in the code behind, but it is in a custom class built specifically for the view. The code behind is often completely empty. At first I wondered why not just put all the ViewModel code in the code behind. The reason is that the code behind is too tightly bound to the UI and we want looser coupling. One immediate advantage we get is the ability to unit test the ViewModel separately from the View.

This walkthrough uses Visual Studio 2013 but should work with versions as far back as 2010.

You can use many data sources for the model. I'm going to use SQL Server because most professional applications will use a database server of some kind. You can use SQL Server Express if you want. I'm going to use Framework Entity as my model because it does so much of the work for me.

    1. Create a new database in SQL Server called MVVM_Walkthrough
    2. Create a new table called Config using the following SQL script

USE [MVVM_Walkthrough]
GO
CREATE TABLE [dbo].[Config](
[Key] [varchar](50) NOT NULL,
[Value] [varchar](1000) NULL,
 CONSTRAINT [PK_Config] PRIMARY KEY CLUSTERED 
(
[Key] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

    3. Insert a single row into Config
INSERT INTO Config VALUES ('ApplicationName','MVVM Walkthrough')

    4. Start a new Visual Studio Project (File -> New -> Project)
    5. In the left panel chose Visual Basic, then Windows
    6. In the right panel chose WPF Application. 
    7. Rename the project to MVVM_Walkthrough and click [OK]

Continue this walkthrough in MVVM Part 1


No comments:

Post a Comment