MVVM Development Mode Simple instance MVVM Demo "Cont."

Source: Internet
Author: User

This article will go on to the next article, about three points: (Universal App)

1. Add the Product collection, bind to the list

2. Events when the Add option to click the ListBox changes (to attach dependency properties, unlike button click events)

3. Get saved data to storage by using custom classes in JSON

-------------------------------------------------

1. Add collection, bind list, support operable

Add fields, properties in Productviewmodel:

Private Observablecollection<productmodel> _products;  Public observablecollection<productmodel> product//Products Collection
{ getreturn _products;} Set  {SetProperty (refthis. _products, value); }}

and add instantiation statements in the constructor

 Public Productviewmodel () {new observablecollection<productmodel>();}

Foreground ListBox code

< In view background, this.   DataContext = product; That means Listbox.datacontext is the same >

<listbox itemssource="{Binding products}"> <ListBox.ItemTemplate> <        datatemplate> <StackPanel> <textblock text="{Binding ProductId}"/> <textblock text="{Binding ProductName}"/> <textblock text="  {Binding UnitPrice} "/> </StackPanel> </DataTemplate> </ListBox.ItemTemplate></ListBox>

Overwrite the event that holds the data as

 Public void saveproduct () {  //await new Messagedialog ("Save"). Showasync ();  Products.add (currentproduct); //Add data to the collection }

Each time you enter a number, save, and the listbox data will increase. (You can try to implement the delete yourself.) )

2. Add an event to the ListBox (equivalent to selectedchanged) we're going to use dependency properties

Add a Selectionchangedbehavior class

 Public Static classSelectionchangedbehavior { Public Static ReadOnlyDependencyProperty Selectionchangedcommandproperty =dependencyproperty.registerattached ("Selectionchangedcommand",                typeof(ICommand),typeof(Selectionchangedbehavior),NewPropertyMetadata (NULL,NewPropertychangedcallback (seletionchangedpropertychangedcallback));  Public StaticICommand Getselectionchangedcommand (DependencyObject d) {return(ICommand) d.getvalue (Selectionchangedcommandproperty); }         Public Static voidSetselectionchangedcommand (DependencyObject D, ICommand value) {D.setvalue (Selectionchangedcommand        property, value); }         Public Static voidSeletionchangedpropertychangedcallback (DependencyObject D, DependencyPropertyChangedEventArgs e) { ((ListBox) d). SelectionChanged+ = (ss, ee) = ={ListBox LV= SS asListBox; Getselectionchangedcommand (LV). Execute (LV.            SelectedItem);        }; }    }

In the View.xaml

Add Reference xmlns:behavior= "Using:SimpleMVVMExample.Common" position for the above class location

Adding attributes to a ListBox

<listbox itemssource="{Binding products}"                           behavior: Selectionchangedbehavior.selectionchangedcommand="{Binding Selectionchangedcommand}"   >

Now go to Productviewmodel realize Selectionchangedcommand;

PrivateICommand _selectionchangedcommand; PublicICommand Selectionchangedcommand {Get            {                if(_selectionchangedcommand = =NULL) _selectionchangedcommand=NewRelaycommand (selectionchanged); return_selectionchangedcommand; }        } Public voidSelectionChanged (Objectparameter) {ProductModel ProductModel= parameter asProductModel; //this has been acquired.//specifically what to do to deal with it yourself}

3. Use life cycle to save and extract data to Settings

A. Custom class conversion to JSON

ProductViewModel.cs

 Public voidSaveData () {varSettings =ApplicationData.Current.LocalSettings; stringJSON = This.            Stringify (); Settings. values["ViewModel"] =JSON; }        Private stringstringify () {jsonobject jsonobject=NewJsonobject (); Jsonarray Jsonarray=NewJsonarray (); foreach(ProductModel iteminchProducts ) {Jsonarray.add (item.            Tojsonobject ()); } Jsonobject Products=NewJsonobject (); Products. Setnamedvalue ("Productskey", Jsonarray); Products. Setnamedvalue ("NewId", Jsonvalue.createnumbervalue (_productid)); Jsonobject.setnamedvalue ("Savekey", products);returnjsonobject.stringify (); }

ProductModel.cs

 Publicjsonobject Tojsonobject () {jsonobject jsonobject=NewJsonobject (); Jsonobject.setnamedvalue ("Namekey", Jsonvalue.createstringvalue (ProductName)); Jsonobject.setnamedvalue ("IdKey", Jsonvalue.createnumbervalue (ProductId)); Jsonobject.setnamedvalue ("Pricekey", Jsonvalue.createnumbervalue (Double) (UnitPrice)) ; Jsonobject Product=NewJsonobject (); Product. Setnamedvalue ("ProductKey", Jsonobject); returnproduct; }

Self-drawn structure ...

B.json Converting to Custom classes

ProductViewModel.cs:

 Public voidGetData () {stringsetting = applicationdata.current.localsettings.values["ViewModel"].            ToString (); Productviewmodel Productviewmodel=NewProductviewmodel (setting);  This. _productid =Productviewmodel._productid;  This. _products =productviewmodel.products; }         PublicProductviewmodel (stringjsonstring) {
this. Products = new observablecollection<ProductModel> ();
Jsonobject Jsonoject=Jsonobject.parse (jsonstring); This. ProductId = (int) Jsonoject.getnamedobject ("Savekey"). Getnamednumber ("NewId"); foreach(varIteminchJsonoject.getnamedobject ("Savekey"). Getnamedarray ("Productskey",NewJsonarray ())) { if(item. ValueType = =jsonvaluetype.object) { This. Products.add (NewProductModel (item. GetObject ())); } } }

ProductModel.cs

 PublicProductModel (Jsonobject jsonobject) {jsonobject productobject= Jsonobject.getnamedobject ("ProductKey"); if(Productobject! =NULL)            {                 This. ProductId = (int) Productobject.getnamednumber ("IdKey");  This. ProductName = (string) Productobject.getnamedstring ("Namekey");  This. UnitPrice = (decimal) Productobject.getnamednumber ("Pricekey"); }        }

C.view life cycle

  private  void  Navigationhelper_        LoadState (object   sender, Loadstateeventargs e) { if  (ApplicationData.Current.LocalSettings.Values.ContainsKey (
   
     " 
    viewmodel  
    "  
    )) {product.            GetData (); }}  
    private  
    void  Navigation Helper_savestate (
    object  
     sender, Savestateeventargs e) {product.        SaveData (); }
   

Note: In the previous article, MVVM does not include any methods in the model, and the method in the model should not be standardized when the JSON is converted here.
Can be implemented in Productviewmodel. Here is just a way to do the conversion. Write in ViewModel save, remove settings content is same.

Here's the demo: for Universal APP

Simplemvvmexample Demo Download

MVVM Development Mode Simple instance MVVM Demo "Cont."

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.