Silverlight-Brief Introduction of MVVM Framework

This post focuses on the usage of  MNNM framework by taking MVVM Light Tooklit as example. Firstly, we need to download MVVM framework from http://mvvmlight.codeplex.com. Then install it. Open VS2010 and create a new project.

  • Tip: MVVM includes Model, ViewMode, View three levels.
  • Model: Entity class level, which is used to save all the needed entity classes.
  • ViewMode: Logic level, which is a big entity class to operate Model and View interface level and offers properties to bind to View level.
  • View: Interface display level. We just need to use its xaml code to bind corresponding ViewMode level properties.

1. In the following MainPage.xaml code, View level is bound to ViewMode level.  It is MainViewModel.cs class.

<UserControl x:Class=“MvvmLight1.MainPage”

             xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;

             xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml&#8221;

             xmlns:d=http://schemas.microsoft.com/expression/blend/2008&#8221;

             xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006&#8221;

             mc:Ignorable=“d”

             Height=“300”

             Width=“300”

             DataContext=“{Binding Main, Source={StaticResource Locator}}”>

    <! —aBind static resource in App.xaml here to link MainViewModel class (ViewMode level) and MainPage.xaml code is View level–>

        <UserControl.Resources>

            <ResourceDictionary>

                <ResourceDictionary.MergedDictionaries>

                    <ResourceDictionary Source=“Skins/MainSkin.xaml” />

                </ResourceDictionary.MergedDictionaries>

            </ResourceDictionary>

        </UserControl.Resources>

        <Grid x:Name=“LayoutRoot”>

            <TextBlock FontSize=“36” FontWeight=“Bold” Foreground=“Purple” Text=“{Binding Welcome}” VerticalAlignment=“Center” HorizontalAlignment=“Center” TextWrapping=“Wrap” Margin=“12,25,20,171” />

            <Button Content=“{Binding BtnContent}” Height=“23” HorizontalAlignment=“Left” Margin=“12,178,0,0” Command=“{Binding ShowMessage}” Name=“button1” VerticalAlignment=“Top” Width=“75” />

            <Button Content=“Click to Change” Height=“23” HorizontalAlignment=“Left” Command=“{Binding ChangeText}” Margin=“187,178,0,0” Name=“button2” VerticalAlignment=“Top” Width=“75” />

        </Grid>

    </UserControl>

2. Then, ViewMode level. We state some string properties to bind to display content of View level. Then, send events and handling methods by using Command for mouse clicking method and set binding. If so, we can separate click events of foreground from background directly and inherit InotifyProperty connector to make ViewModel property be reflected to View level when changing and View level foreground presentation be changed when changing ViewModel properties in Command.

using GalaSoft.MvvmLight;

using System.Windows.Input;

using GalaSoft.MvvmLight.Command;

using System.Windows;

using System.ComponentModel;

namespace MvvmLight1.ViewModel

{

    ///<summary>

    ///This class contains properties that the main View can data bind to.

    ///<para>

    ///Use the <strong>mvvminpc</strong>snippet to add bindable properties to this ViewModel.

    ///</para>

    ///<para>

    ///You can also use Blend to data bind with the tool’s support.

    ///</para>

    ///<para>

    ///See http://www.galasoft.ch/mvvm/getstarted

    ///</para>

    ///</summary>

    public class MainViewModel : ViewModelBase, INotifyPropertyChanged

    {

        public string Welcome

        {

            get

            {

                return “Welcome to Use MVVM Light! “;

            }

        }

        ///<summary>

        ///Class Initialization

        ///</summary>

        public MainViewModel()

        {

            _btnContent = “Click”;

            RegistCommand();

        }

        //A. Bind Property

        private string _btnContent;

        public string BtnContent

        {

            set

            {

                _btnContent = value;

                NotifyPropertyChanged(“BtnContent”);

            }

            get

            {

                return _btnContent;

            }

        }

        //B. 1 State to Bind Click Event

        public RelayCommand ShowMessage { get; set; }

        //Use Registration of C step and Connect Command and Method to Run

        private void showmsg()

        {

            MessageBox.Show(“Succeed to bind command to interface layer!);

        }

        //B.2 Change Control Presentation Text on Interface

        public RelayCommand ChangeText { get; set; }

        //Operation to Change Text

        private void changeTxt()

        {

            BtnContent = “It has been changed.”;

        }

        //Text Can Be Changed or not

        private bool canchangeTxt()

        {

            if (BtnContent == “Click”)

            {

                return true;

            }

            else

            {

                return false;

            }

        }

        //C. Register for All Methods

        private void RegistCommand()

        {

            //C.1 Specify function showmsg() which is needed to execute.

            ShowMessage = new RelayCommand(() => showmsg());

            //Execute canchangeTxt() firstly to verify if text can be change. If can, execute changeTxt().

            ChangeText = new RelayCommand(() => changeTxt(), () => canchangeTxt());

        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void NotifyPropertyChanged(string propertyName)

        {

            if (PropertyChanged != null)

            {

                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

            }

        }

    }

}

3. Here, we don’t use Model level. It is usually used for creating entity sets to bind control like DataGrid.

Two Components Recommend:

Spire.Doc, is used to operate MS Word document for .Net and Silverlight, including basic manipulations (generate, open, edit documents), mail merge and other Word functions manipulations.

Spire.XLS, is used to operate MS Excel for .NET and Silverlight, including basic manipulations (generate, open, edit files), chart creation and data exporting.

Advertisements

Author: janewdaisy

.NET Program Beginner. Share methods about how to use C#/VB.NET to export data, operate Word, Excel, PDF and other useful skills.

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