UWP lawyer Queries MVVM

Source: Internet
Author: User

App Introduction

Lawyer query is based on the aggregation data of the lawyer query interface do, this interface is currently inactive, but, because I was previously applied, so, can also use, should be unable to apply again .

Development One, Httphelper

Since is the request interface, that is the request method, here is more commonly used httpclient, it is more convenient to use, a separate package of a Httphelper class, specifically used as a basis for the connection

 Public Static classBaseservice {/// <summary>        ///cookies When accessing the server/// </summary>         Public StaticCookiecontainer Cookiescontainer; /// <summary>        ///send a GET request to the server to return data from the server reply/// </summary>        /// <param name= "url" >Address</param>        /// <returns></returns>         Public Async Statictask<string> Sendgetrequest (stringURL) {            Try{HttpClient Client=NewHttpClient (); Httpresponsemessage Response=awaitClient. Getasync (NewUri (URL)); Response.                Ensuresuccessstatuscode (); return awaitResponse.            Content.readasstringasync (); }            Catch(Exception ex) {return NULL; Throw(ex); }        }        /// <summary>        ///send a POST request to the server to return the server reply data/// </summary>        /// <param name= "url" >Address</param>        /// <param name= "Body" >Newspaper Style</param>        /// <returns></returns>         Public Async Statictask<string> Sendpostrequest (stringUrlstringbody) {            Try{HttpClient Client=NewHttpClient (); Httpresponsemessage Response=awaitClient. Postasync (NewUri (URL),NewFormurlencodedcontent (New[] {Newkeyvaluepair<string,string> ("", Body)}); Response.                Ensuresuccessstatuscode (); return awaitResponse.            Content.readasstringasync (); }            Catch(Exception ex) {return NULL; Throw(ex); }        }    }
Baseservice

Network requests are definitely asynchronous requests, the UWP is more commonly used in the async, await mode, very convenient, because the interface return results are in JSON form, so, Newtonsoft.json to handle serialization and deserialization.

/// <summary>    ///JSON returns results///Description: The errormess must be rewritten, otherwise there is no error returning the message/// </summary>     Public Abstract classResultinfohelper {/// <summary>        ///passing in URLs and parameters, parsing returns JSON information, and returning results/// </summary>        /// <typeparam name= "T" >parameter Type</typeparam>        /// <param name= "_url" >URL address</param>        /// <param name= "args" >Related Parameters</param>        /// <returns></returns>         Public AsyncTask<t> getresultinfogethelper<t> (string_url,params Object[] args) {            stringURL =string.            Format (_url, args); stringResulturl =awaitbaseservice.sendgetrequest (URL); Errormess<T>(Resulturl); T resultlist= jsonconvert.deserializeobject<t>(Resulturl); returnresultlist; }        /// <summary>        ///pass in the URL and body, parse back the JSON information, and return the result/// </summary>        /// <typeparam name= "T" >parameter Type</typeparam>        /// <param name= "_url" >URL address</param>        /// <param name= "Body" >Incoming Body</param>        /// <returns></returns>         Public AsyncTask<t> getresultinfoposthelper<t> (string_url,stringbody) {            stringResulturl =awaitbaseservice.sendpostrequest (_url, body); Errormess<T>(Resulturl); T resultlist= jsonconvert.deserializeobject<t>(Resulturl); returnresultlist; }        /// <summary>        ///error Message/// </summary>        /// <typeparam name= "T" ></typeparam>        /// <param name= "Resulturl" ></param>        protected Abstract voidErrormess<t> (stringResulturl); }
Resultinfohelper

Abstract is used here for other projects can also use this httphelper, rewrite errormess convenient for different projects to throw different errors.

The advantage of using the params object[] args as a parameter is that you can not qualify the type and number of parameters.

Second, SEARCHLAWYER.UWP1, according to the interface return, design entity class

Lawyer query interface is similar to the return of this form, is reason, result, error_code, since, there is a unified law, it is very easy to establish the entity class, create a info<t>.

Info<t> for all returned overall styles, by passing in different T types, to ensure that result is a different type of generic collection, so that it is convenient to receive the returned data, such as info<lawyer>

2.Request Interface

Write a getinfohelper<m> inheritance resultinfohelper, overriding the Errormess method

 Public classGetinfohelper<m>: resultinfohelper {/// <summary>        ///overriding the error method/// </summary>        /// <typeparam name= "T" ></typeparam>        /// <param name= "Resulturl" ></param>        protected Override Async voidErrormess<t> (stringResulturl) {            if(typeof(T). name==typeof(info<m>). Name) {Info<M> error = Jsonconvert.deserializeobject<info<m>>(Resulturl); if(Error.error_code! =0)                {                    await(NewMessagedialog ("Error code:"+ Error.error_code +"\ r \ n"+"error message:"+Constant.constantvalue.error[error.error_code]).                    Showasync (); return; }            }        }    }
Getinfohelper

Here, you need to distinguish whether typeof (T) and typeof (Info<m>) are the same type, and if they are the same type, you can do the following

The reason for this is that it is designed for different return types without having to write multiple methods

3. Write the View page

Because the page is either lawyer query, or argument query, so the content format of the page display is the same, in order not to repeat work, need to write a unified ItemTemplate (written in the style file), if the style with binding is no problem, But if the use of X:bind will be wrong , but Microsoft gave the X:bind more efficient than binding, so, I can not bypass this problem, the solution took a small half a day, to solve. You can refer to my post X:bind does not support style files or this XAML file must be a code-behind class to use the {x:bind} workaround

4, write ViewModel page

Because there is no complex business logic to discriminate, the VM page is pretty simple, depending on the buttons you don't use, calling different requests

It is important to note that because there is no x:static in the UWP, if you pass an enumeration as a parameter, you must use the following notation in order to get to the parameter value, otherwise the VM page will always receive the first one of the enumeration

<ButtonContent= "Query"Command="{Binding Searchcommand}">  <Button.commandparameter>    <Constant:method>Lawyerbyprovince</Constant:method>  </Button.commandparameter></Button>

In order to move down, dynamically refresh the list, that is, continue to request data, classes need to inherit observablecollection<lawyer> and Isupportincrementalloading, This I am the "fully Open source" blog Garden client UWP version with the source code, with the app (next) in the Zhou Chihi, but found a problem, if I have a small number of returns, the display results, but also pop up a no query to the data error, tracking code found that this method will request two times, so , do write changes, is to determine whether the number is less than the set number of return bar, if so, set the Hasmoreitems to false, to prevent the request again.

Summarize

The code aspect is not difficult, has seen the Microsoft to provide the development video, basically can get the UWP development, but, because has been doing the WPF, does a uwp practice practiced hand, discovered, the place is quite many, said back, the development uwp is quite interesting, the development process learned many things, It's really something that looks easy, and it doesn't have to be easy to come true.

Hopefully, more and more developers are paying attention to UWP development to make this ecosystem better.

Source has been put on GitHub

UWP lawyer Queries MVVM

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.