The MVVM framework in Windows phone

Source: Internet
Author: User

MVVM (Model View ViewModel) is a pattern developed by the MVC and MVP model, which is designed to split the code and interface of the application so that the interface development can focus more on the design interface and makes the UI interface easier to transform and test. Here's a look at the main features of these 3 layers

1.Model Layer

The data access layer, typically defined as one or more classes, represents the data in an object-oriented manner.

2.View Layer

Presentation layer, implementation of UI interface, and interaction with viewmodel layer through binding and command

3.ViewModel Layer

It is responsible for the information conversion between view and model, the command of view is uploaded to model, and the data transfer to and from the view layer is realized through binding.

The following is an instance of data binding for an MVVM pattern:

Ideas:

1. Define an entity class (model layer) to hold the data.

2. Create a ViewModel layer: Declare a collection Class (observablecollection<t>) as the data source for the binding, and the ViewModel layer must be the INotifyPropertyChanged interface that implements the This allows the binding to be notified in a timely manner when the data source changes to change the target value (in the View layer).

3. Create a view layer. If you want to bind the data in the ViewModel layer, you must reference the namespace in the ViewModel layer, add it to resource, and set a key (set to "food" in this instance). The resources in the resource are then assigned to the DataContent property in the grid control, and the data source in the ViewModel layer is available in the grid.

The Food.cs code is as follows (model layer)

namespacebindingdatademo.model{ Public classFood { Public stringName {Get; Set; }         Public stringDescription {Get; Set; }         Public stringIconuri {Get; Set; }         Public stringType {Get; Set; }    }}
Food.cs

The FoodViewModel.cs code is as follows (ViewModel layer)

usingSystem;usingSystem.ComponentModel;usingBindingdatademo.model;usingSystem.Collections.ObjectModel;namespacebindingdatademo.viewmodel{ Public classfoodviewmodel:inotifypropertychanged {PrivateObservablecollection<food>_allfood;  PublicObservablecollection<food>Allfood {Get            {                if(_allfood = =NULL) _allfood=NewObservablecollection<food>(); return_allfood; }            Set            {                if(_allfood! =value) {_allfood=value; Notifypropertychanged ("Allfood"); }            }        }         PublicFoodviewmodel () {Try{food item0=NewFood () {Name ="Tomato", Iconuri ="Images/tomato.png", Type ="Healthy", description="the tomato tastes good. " }; Food Item1=NewFood () {Name ="Eggplant", Iconuri ="Images/beer.png", Type ="notdetermined", Description ="I don't know if it tastes good. " }; Food item2=NewFood () {Name ="Ham", Iconuri ="Images/fries.png", Type ="unhealthy", Description ="this is unhealthy food. " }; Food Item3=NewFood () {Name ="Sandwiches", Iconuri ="Images/hamburger.png", Type ="unhealthy", description="KFC's Delicious? " }; Food ITEM4=NewFood () {Name ="Ice Cream", Iconuri ="Images/icecream.png", Type ="Healthy", Description ="for the children to eat. " }; Food ITEM5=NewFood () {Name ="Pizza", Iconuri ="Images/pizza.png", Type ="unhealthy", description="this is very good. " }; Food ITEM6=NewFood () {Name ="Pepper", Iconuri ="Images/pepper.png", Type ="Healthy", Description ="I don't like to eat this stuff. " };                Allfood.add (ITEM0);                Allfood.add (ITEM1);                Allfood.add (ITEM2);                Allfood.add (ITEM3);                Allfood.add (ITEM4);                Allfood.add (ITEM5);            Allfood.add (ITEM6); }                  Catch(Exception e) {System.Windows.MessageBox.Show ("Exception:"+e.message); }           }                //Defining propertychanged Events         Public EventPropertyChangedEventHandler propertychanged;  Public voidNotifypropertychanged (stringPropertyName) {            if(PropertyChanged! =NULL) {propertychanged ( This,NewPropertyChangedEventArgs (PropertyName)); }        }      }}
FoodViewModel.cs

The MainPage.xaml code is as follows (view layer)

<phone:phoneapplicationpage x:class="Bindingdatademo.mainpage"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="Http://schemas.microsoft.com/winfx/2006/xaml"Xmlns:phone="Clr-namespace:microsoft.phone.controls;assembly=microsoft.phone"Xmlns:shell="Clr-namespace:microsoft.phone.shell;assembly=microsoft.phone"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"XMLNS:MC="http://schemas.openxmlformats.org/markup-compatibility/2006"Xmlns:my="Clr-namespace:bindingdatademo.viewmodel"mc:ignorable="D"D:designwidth="480"d:designheight="768"FontFamily="{StaticResource Phonefontfamilynormal}"FontSize="{StaticResource Phonefontsizenormal}"Foreground="{StaticResource Phoneforegroundbrush}"supportedorientations="Portrait"orientation="Portrait"shell:SystemTray.IsVisible="True"> <phone:PhoneApplicationPage.Resources> <my:foodviewmodel x:key=" Food"/> </phone:PhoneApplicationPage.Resources> <grid x:name="LayoutRoot"Background="Transparent"> <Grid.RowDefinitions> <rowdefinition height="Auto"/> <rowdefinition height="*"/> </Grid.RowDefinitions> <stackpanel x:name="Titlepanel"grid.row="0"margin="12,17,0,28"> <textblock x:name="Applicationtitle"text="MY Application"style="{StaticResource Phonetextnormalstyle}"/> <textblock x:name="PageTitle"text="Data Binding"margin="9,-7,0,0"style="{StaticResource Phonetexttitle1style}"/> </StackPanel> <grid x:name="Contentpanel"grid.row="1"margin="12,0,12,0"datacontext="{StaticResource Food}"> <listbox x:name="ListBox"Horizontalcontentalignment="Stretch"Itemssource="{Binding Allfood}"> <ListBox.ItemTemplate> <DataTemplate> <stackpa Nel orientation="Horizontal"Background="Gray"Width=" the"margin="Ten"> <image source="{Binding Iconuri}"Stretch="None"/> <textblock text="{Binding Name}"Fontsize=" +"Width=" Max"/> <textblock text="{Binding Description}"Fontsize=" -"Width="280"/> </StackPanel> </DataTemplate> </listbox.item template> </ListBox> </Grid> </Grid></phone:PhoneApplicationPage>
MainPage.xaml

The MVVM framework in Windows phone

Related Article

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.