Mvvm light starts

Source: Internet
Author: User

Address: http://jesseliberty.com/2011/01/04/wpfs-mvvm-light-toolkit-soup-to-nuts-part-i/

It's just a free translation. If you don't need it, you don't have to worry about it.

 

Mvvm provides the best mode for WP7 development. Currently, mvvm has many excellent frameworks, making mvvm development easier. I personally prefer mvvm light, so I will focus on it now.

 

Installation steps:

Codeplex address: http://mvvmlight.codeplex.com/

You can also download from its official website: http://www.galasoft.ch/mvvm/

Download and install the latest version. Mvvm light toolkit V4 Beta 1 is installed here. After installation, you can see the mvvm light template in vs2010.

 

Create an mvvm application to learn some basic information. We will discuss more interesting topics in the future, such as behaviors and messages.

 

Create an application

Open vs2010, click "Create Project", and select the mvvm light (wp71) template. Now most WP mobile phones have been upgraded to mango. You can also use the WP7 template.

 

Enter a project name. The default mvvmlight1 is used here. Compile and run the program, and press the application to display "Welcome to mvvm light ". OK.

 

View view and viewmodel

The template automatically adds the following directories: model, viewmodel, and some default CS code.

Open mainviewmodel. CS and you will find several string attributes:Welcometitle.These attributes are bound to mainpage. XAML,

   1: <StackPanel x:Name="TitlePanel"

   2:                     Grid.Row="0"

   3:                     Margin="24,24,0,12">

   4:             <TextBlock x:Name="ApplicationTitle"

   5:                        Text="{Binding ApplicationTitle}"

   6:                        Style="{StaticResource PhoneTextNormalStyle}" />

   7:             <TextBlock x:Name="PageTitle"

   8:                        Text="{Binding PageName}"

   9:                        Margin="-3,-8,0,0"

  10:                        Style="{StaticResource PhoneTextTitle1Style}" />

  11:         </StackPanel>

  12:  

  13:         <!--ContentPanel - place additional content here-->

  14:         <Grid x:Name="ContentGrid"

  15:               Grid.Row="1">

  16:  

  17:             <TextBlock Text="{Binding WelcomeTitle}"

  18:                        Style="{StaticResource PhoneTextNormalStyle}"

  19:                        HorizontalAlignment="Center"

  20:                        VerticalAlignment="Center"

  21:                        FontSize="40" 

  22:                        TextWrapping="Wrap" 

  23:                        TextAlignment="Center" />

  24:         </Grid>

You must set mainviewmedel to the datacontext of mainpage. XAML. This is defined in the <Phone: phoneapplicationpage> section at the beginning of the page:

Datacontext = "{binding main, source = {staticresource locator }}"

   1:  <phone:PhoneApplicationPage
   2:                              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   3:                              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   4:                              xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
   5:                              xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
   6:                              xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
   7:                              xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
   8:                              xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" xmlns:GalaSoft_MvvmLight_Command="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WP71" x:Class="MvvmLight1.MainPage"
   9:                              FontFamily="{StaticResource PhoneFontFamilyNormal}"
  10:                              FontSize="{StaticResource PhoneFontSizeNormal}"
  11:                              Foreground="{StaticResource PhoneForegroundBrush}"
  12:                              SupportedOrientations="Portrait"
  13:                              Orientation="Portrait"
  14:                              mc:Ignorable="d"
  15:                              d:DesignWidth="480"
  16:                              d:DesignHeight="768"
  17:                              shell:SystemTray.IsVisible="True"
  18:                              DataContext="{Binding Main, Source={StaticResource Locator}}">

 

Please note that this is through staticresourceLocatorDefined.

 

Viewmodellocator

Viewmodellocator is the core of mvvm light. It is worth studying how it works. This is a good method, but it is not the only method. You can set the relationship between a view (mainpage) and Its Model (mainviewmodel.

 

This static resource lacator is defined in APP. XAML:

   1: <Application.Resources>

   2:         <!--Global View Model Locator-->

   3:         <vm:ViewModelLocator x:Key="Locator"

   4:                              d:IsDataSource="True" />

   5:     </Application.Resources>

Finally, you can find the viewmodellocator constructor in the viewmodellocator. CS file (which is automatically created in the viewmodel directory when you create a project), which registers the mainviewmodel type:

   1: SimpleIoc.Default.Register<MainViewModel>();

In this way, the view of mainpage is connected with its viewmodel.

 

Some work needs to be done when adding the second page, but the code has been put into code-snippets, which can be easily entered.

 

Add second page

For more details, add the second page.

 

First, right-click the project, add a new folder, right click Add item, select mvvm page (WP7), and name it page2.xaml.

View the <Phone: phoneapplicationpage> section of page2.xaml to see its datacontex:

Datacontext = "{binding viewmodelname, source = {staticresource locator }}"

 

We also need to create its viewmodel for it. Add an item in the viewmodel directory, select mvvmviewmodel (WP7), and name it page2viewmodel. CS.

 

Add the following public attributes to viewmodel:

   1: public string ApplicationTitle

   2: {

   3:    get

   4:    {

   5:       return "MVVM LIGHT";

   6:    }

   7: }

   8:  

   9: public string PageName

  10: {

  11:    get

  12:    {

  13:       return "Page 2";

  14:    }

  15: }

  16:  

  17: public string Welcome

  18: {

  19:    get

  20:    {

  21:       return "Welcome to Page 2";

  22:    }

  23: }

Now connect them. Modify the datacontext attribute of page2.xaml to page2.

Datacontext = "{binding page2, source = {staticresource locator }}"

 

Use code snippets

 

Open viewmodellocator. CS and view its constructor. You can useMvvmlocatorpropertyCode segment. Locate the input outside the constructor.Mvvmlocatorproperty,Press TAB twice to modify the viewmodel name. Note that because the static viewmodellocator () constructor already exists, the automatically generated parameters are repeated, copy the statements and paste them to the original constructor. The modified code is as follows:

   1: static ViewModelLocator()

   2:         {

   3:             ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

   4:  

   5:             if (ViewModelBase.IsInDesignModeStatic)

   6:             {

   7:                 SimpleIoc.Default.Register<IDataService, Design.DesignDataService>();

   8:             }

   9:             else

  10:             {

  11:                 SimpleIoc.Default.Register<IDataService, DataService>();

  12:             }

  13:  

  14:             SimpleIoc.Default.Register<MainViewModel>();

  15:             

Simpleioc. Default. register <page2viewmodel> ();

  16:         }

  17: /// <summary>

  18:         /// Gets the Page2ViewModel property.

  19:         /// </summary>

  20:         [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",

  21:             "CA1822:MarkMembersAsStatic",

  22:             Justification = "This non-static member is needed for data binding purposes.")]

  23:         public Page2ViewModel Page2

  24:         {

  25:             get

  26:             {

  27:                 return ServiceLocator.Current.GetInstance<Page2ViewModel>();

  28:             }

  29:         }

 

Next step: Use Behavior and message to implement navigation

The rest is to add a button on the first page and navigate to the second page. Of course, it is very simple in code behind. You may say: Isn't it used? Navigationservice. navigate (new system. Uri ("/page2.xaml", system. urikind. Relative ));

This is certainly acceptable, but we want to use mvvm to implement it and use behavior and messages.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.