WPF and MVVM tutorial 06, start up form.

Today we are going to create the start-up form of our project and use the first ViewModel to run the application logic.

The result we want to obtain will be:

image

The View Model for the Startup form.

In our project, let’s go to the ViewModel section and create a new class. This class will inherit from the basic View Model class like the code below:

  1: public class StartViewModel : ViewModel {
  2: 
  3:    public StartViewModel() {
  4: 
  5:    }
  6: }

Then we need to create 2 commands that we will then associate to two buttons in our XAML form. One will start the application and one will shut-down the application.

This is the implementation we need to do in our ViewModel in order to create the Relay Command:

  1: public ViewCommand startCommand;
  2: public ViewCommand StartCommand {
  3:     get {
  4:         if (startCommand == null)
  5:             startCommand = new ViewCommand
  6:                  (param => this.StartApplication());
  7:         return startCommand;
  8:     }
  9: }
 10: 

Then we need a delegate for the relay command in this way:

  1: private void StartApplication() {
  2:   NavigationActions.OpenCustomersView();
  3: }
  4: 

The first XAML Form of our Application.

I am not a guru in windows design, especially the fancy UI but the final project will have a startup form like this one:

image

First of all add a new XAML form into the UI layer and then let’s see at the XAML code:

  1: <Window x:Class="MVVM.WPFView.Start"
  2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4:     xmlns:vm="clr-namespace:MVVM.ViewModel;assembly=MVVM.ViewModel"
  5:         Title="MVVM AdventureWorks Application." 
  6:         Height="500" Width="500"
  7:         WindowStartupLocation="CenterScreen" WindowState="Normal"
  8:         WindowStyle="None">
  9: 

If you look at the line 4, we added a reference to our viewmodel namespace. In this way we can use in a declarative way the objects in the viewmodel namespace, directly into XAML (I personally hate to use procedural code into XAML!)

  1:     <Window.DataContext>
  2:         <vm:StartViewModel />
  3:     </Window.DataContext>
  4: 

Then we add as a resource, the StartViewModel view model into our Window. In this way when the window will load the XAML declaration will inform the CLR to load a default instance of our view model.

Now let’s view the two buttons:

  1: <Button Name="btnStart" Margin="5" 
  2: IsDefault="True" 
  3: Command="{Binding Path=StartCommand}">

The binding will be the Relay Command we have previously created in the View model class. Easy right?

Now, the next step will be to build the View model to show all the customers. Then we will build some specific command for the C.R.U.D. operations.

Stay tuned!

Tags: