Silverlight 4 Business Application Part 3 of n


Implementation of the Login Dialog in Silverlight application by using MVVM pattern

imageIn the third article, of the series of the Silvelright Business application development, I will present Login dialog implementation by applying  MVVM pattern. Problems looks very simple but if you want to implement in MVVM fashion you could encounter some problems. MVVM pattern became very popular in Silverlight and WPF application development and it seams to be standard development pattern. More information about the pattern can be found on various blogs, internet sites and forums.  One of the first and the best article about MVVM patern is MSND article about MVVM patern by Josh Smith and it can be found here.

This tutorial assume that you know basic principles of the MVVM pattern as well as Silverlight application.

In tis tutorial we will use the MVVM toolkit the implementation of the MVVM pattern developed by Laurent Bugnion, which you can download at http://mvvmlight.codeplex.com/. Before we start the tutorial, download the toolkit and install it as it decribed on the codeplex site.

The idea of the Login dialog, presented here, not depends of the MVVM light toolkit, so it can be easily implemented with other MVVM pattern, like PRISM and others.

Start Visual Studio 2010, and select File->New –>Project, select Silverlight Application in the same way we implemented in Part 2. Instead of Silverlight Aplication, select MvvmLight (SL4) template as picture below shows. After we choose the template, and click OK, Visual Studio designer created Silverlight application which support MVVM pattern.

The picture below shows The New Project dialog window:

image

As you can see Visual Studio created Silverlight application, but not the ASP.NET web application project. For this tutorial we don’t need it.

image

The picture above shows project files and how files are arranged in the project. The folder ViewModel contains the ViewModels implementations. Lets create View folder, it will contain Views implementation.

Implementation of MainView and MainViewModel

MainViewContent will be our main content for the Silverlight application. It will be shown after we logged in.

1. Right Click on the recently created View folder, and choose Add->New Item

2. Select Silverlight User Control and give it name MainViewContent.xaml

image

3. In the XAML file put the following code:

<Grid x:Name="LayoutRoot" Background="White">
        <TextBlock Text="MAIN CONTENT OF THE SILVERLIGHT APPLICATION"
                   HorizontalAlignment="Center"
                   VerticalAlignment="Top"
                   FontSize="16" FontFamily="Arial Black" />
</Grid>

Implementation is simple. Just TextBlox with some text.

Now we need to create MainViewModelContent:

4. Right Click on the ViewModel folder, and choose Add->New Class

5. Name it MainViewModelContent.cs

Implementation of the MainViewModelContent is in the following listing:

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using GalaSoft.MvvmLight;

namespace SLPart3MvvmLoginDialog.ViewModel
{
    public class MainViewModelContent : ViewModelBase
    {

    }
}

The implementation is empty cause we want the empty view model without interaction with the view .

Implementation of LoginView and LoginViewModel

Similar as previous we create LoginView.Xaml and LoginViewModel.cs.

Xaml implementation of the LoginView contains controls and layout depicted in the first picture of the article. Here is the main xaml code:

<Border BorderThickness="1" BorderBrush="Black">
        <Grid x:Name="LayoutRoot1" Background="White">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="120" />
                <ColumnDefinition Width="120" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="40" />
                <RowDefinition Height="30" />
                <RowDefinition Height="28" />
                <RowDefinition Height="28" />
                <RowDefinition Height="40" />
                <RowDefinition Height="28" />
                <RowDefinition Height="*" />
            </Grid.RowDefinitions>

            <Rectangle x:Name="rectangle1" Stroke="Black" StrokeThickness="1" Fill="#FFDE8836" Grid.ColumnSpan="4" />
            <TextBlock Grid.Row="2" x:Name="textBlock2" Text="User Name:" Padding="5" HorizontalAlignment="Right"
                       VerticalAlignment="Center" Grid.Column="1" Margin="0,9" />
            <TextBlock x:Name="textBlock3" Text="Password:" Grid.Row="3" Padding="5" HorizontalAlignment="Right"
                       VerticalAlignment="Center" Grid.Column="1" Margin="0,9" />
            <TextBox Grid.Column="2" Grid.Row="2" x:Name="textBox1" Margin="2" Text="{Binding UserName, Mode=TwoWay}" />
            <PasswordBox Grid.Column="2" Grid.Row="3" x:Name="passwordBox1" Margin="2"  Password="{Binding Password, Mode=TwoWay}"/>

            <Button Content="Cancel" Grid.Column="1" Grid.Row="5" x:Name="radButton1" Margin="5,2" />
            <Button Content="Login" x:Name="radButton2" Grid.Column="2" Grid.Row="5" Margin="5,2" >
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="Click">
                        <mvvmcmd:EventToCommand Command="{Binding LoginCommand, Mode=OneWay}"
                                CommandParameter="{Binding Main, Source={StaticResource Locator}}"/>
                    </i:EventTrigger>
                </i:Interaction.Triggers>
            </Button>
            <TextBlock x:Name="textBlock1" Text="Login Dialog" VerticalAlignment="Center" HorizontalAlignment="Center"
                       Grid.ColumnSpan="2" Margin="10,5,5,12" Grid.Column="1" FontFamily="Portable User Interface"
                       FontSize="20" FontStretch="SemiCondensed" FontWeight="SemiBold" Foreground="Black"/>
        </Grid>
</Border>

The main part of this xaml code above is that the MainViewModel is passed as a parameter of the Login button EventToCommand, and if the login is correct, the LoginModelView change IsLoggedIn property to true. Then main page switch the visibility property of the LoginView to Collapsed, and MainContentView to Visible.

Implementation of the LoginViewModel.cs is show on the next listing:

//Constructor
public LoginViewModel()
  {
    this.LoginCommand = new RelayCommand<object>(this.OnLogging, this.CanLogging);
  }
//Wnen the user click Login button in LoginView
private void OnLogging(object arg)
  {
   var vm = arg as MainViewModel;
   if (vm == null)
      return;

   //proces of logging
   vm.IsLogged = true;
   }

private bool CanLogging(object arg)
   {

     return true;
   }

ModelView coresponding classes is always derived from the ModelViewBase.

Putting all together in MainPage and ManViewModel

Now, when you implemented Login  and MainContent, we need put these objects in to MainPage. The MainPage is responsible of showing and hiding these views.

Implementation of the MainPage.xaml

<Grid x:Name="LayoutRoot">

        <my:MainViewContent Visibility="{Binding Main.IsLogged,
                      ConverterParameter=mainView,
                      Converter={StaticResource MainPageBoolLoginToVisibilityConverter1},
                      Source={StaticResource Locator}}"/>
            <my:LoginView Visibility="{Binding Main.IsLogged,
            ConverterParameter=loginView,
            Converter={StaticResource MainPageBoolLoginToVisibilityConverter1},
            Source={StaticResource Locator}}" HorizontalAlignment="Center" VerticalAlignment="Center" />
    </Grid>

Implementation of the MainViewModel

public const string IsLoggedPropertyName = "IsLogged";
private bool _islogged;
public bool IsLogged
 {
   get
    {
      return _islogged;
    }
   set
    {
      if (value != _islogged)
      {
        _islogged = value;
        RaisePropertyChanged(IsLoggedPropertyName);
      }
    }
  }

public MainViewModel()
  {
    if (IsInDesignMode)
    {
     // Code runs in Blend --> create design time data.
    }
    else
    {
     // Code runs "for real"
    }
}

As you can see we implemented IsLogged property, which is the switch between Login and MainViewContent. With BoolToVisibilityConverter class, we were implemented changing visibility of the Views. The converter class is in the source code of the project attached with this tutorial.
Now at the end we have to implement LoginVieModel and MainContentViewModel in to Locator class.
The implementation is very simple and you can see it in the sourcecode project. Now run the application and clik the Login button, The MainContentView appears.

Summary

This article present the simple technique you can easily implement in your Silverlight application with full fashion of the MVVM pattern.

The source code can be download from  here.

About Bahrudin Hrnjica

PhD in Mechanical Engineering, Microsoft MVP for .NET. Likes .NET, Math, Mechanical Engineering, Evolutionary Algorithms, Blogging.

Posted on 11/12/2010, in .NET, CodeProject and tagged , , , , , . Bookmark the permalink. 1 Comment.

  1. Some really nice and utilitarian info on this internet site, too I conceive the pattern contains fantastic features.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s