MVVM (1) from a logon page)

Source: Internet
Author: User

From http://www.cnblogs.com/Sunpire/archive/2010/12/25/1916913.html

Silverlight uses MVVM mode, but how many people are using MVVM? I don't have one.

Here, I will take a logon page as an example to share with you some of the ideas about Silverlight development,

Including Validation and MVVM.

 

However, I have not learned the official MVVM documentation. In this example, I refactor from an instance,

I am very grateful to you for writing this article.

 

This example uses Silverlight + WCF instead of Silverlight + wcf ria Services,

If you are not familiar with Silverlight + WCF, please first learn this content.

 

This example is divided into three phases:

I. MV mode (Model-View Mode)

Ii. MVVM mode (Model-View-ViewModel Mode)

Iii. MVVM mode and Command

 

Appendix: VS2010 source code download http://files.cnblogs.com/Sunpire/MVVMTutorial.zip

 

Stage 1: MV mode (Model-View Mode)

In fact, you can use the MV mode, which indicates that Silverlight is getting started. How many elements are available from ASP. NET and Windows Form?

If you do not know Binding or Validation, you may want to access data from the UI and verify the data.

 

In this example, the WCF end is very simple, that is, verifying the user name, password, and verification code.

 

User class in WCF
namespace MVVMTutorial.Web.Models
{
[DataContract]
public class User
{
[DataMember]
public string UserName { get; set; }

[DataMember]
public string Password { get; set; }
}
}
Copy code

 

It is easy to generate a four-digit verification code based on the current time. If the user name is a test with no size difference and the password is a test with lower case, the logon is successful.

LoginService. svc
Namespace MVVMTutorial. Web
{
[ServiceContract (Namespace = "")]
[AspNetCompatibilityRequirements (RequirementsMode = AspNetCompatibilityRequirementsMode. Allowed)]
Public class LoginService
{
/// <Summary>
/// A simple verification code is recorded. For simplicity, the verification code is permanently valid.
/// </Summary>
Private static List <string> validationCodes = new List <string> ();

/// <Summary>
/// Generate a simple verification code
/// </Summary>
/// <Returns> </returns>
[OperationContract]
Public string GenerateValidationCode ()
{
String ticks = DateTime. Now. Ticks. ToString ();
System. Text. StringBuilder sb = new System. Text. StringBuilder ();
For (int I = ticks. Length-5; I> = ticks. Length-8; I --)
{
Sb. Append (ticks [I]);
}
If (! ValidationCodes. Contains (sb. ToString ()))
{
ValidationCodes. Add (sb. ToString ());
}
Return sb. ToString ();
}

/// <Summary>
/// Simple logon judgment
/// </Summary>
/// <Param name = "usr"> </param>
/// <Param name = "validationCode"> </param>
/// <Returns> 1: the user name and password are correct; 0: the user name and password are incorrect; 2: The verification code is invalid </returns>
[OperationContract]
Public short Login (Models. User usr, string validationCode)
{
If (! ValidationCodes. Contains (validationCode ))
{
Return 2;
}
If (usr! = Null & usr. UserName. ToLower () = "test" & usr. Password = "test ")
{
Return 1;
}
Else
{
Return 0;
}
}
}
}
Copy code

Next, we will use the Silverlight client to generate the agent class of LoginService. svc.

The User class code is generated in Reference. cs of the agent LoginProxy,

I will Copy it and place it in a low-level class library project, such as the User. cs file of the Models project,

Why? This is because of the needs of Validation.

 

Validation needs to use various attributes in System. ComponentModel. DataAnnotations,

For example, UserName is written as follows:

UserName in User. cs

It is verified as required, the length is 3-6 characters, only letters and numbers can be entered, and "User Name" is displayed in the Label of the front-end UI.

 PS: For Silverlight Validation, refer to the blog http://www.cnblogs.com/jv9/archive/2010/09/27/1836394.html of jv9

 

Change the namespace of the User to be the same as that of the User in WCF, generate the Models project, and then update LoginProxy,

In this way, Reference. cs no longer contains the definition of User.

 

The Models project stores various Models. In actual projects, Models with an absolute large number come from

Entity. In this example, a ValidationModel is added for the verification code to represent the verification code model. This model only has

A logic "Verification code must be the same as the verification code obtained from WCF ". Actually, this Model does not exist on the WCF end. Add this

Model is also used to apply Binding and Validation in the UI.

 

Next, let's look at the View section:

 

LoginPage. xaml

Binding and ValidationSummary are used here. I personally think this is a sign of getting started with Silverlight :)

Is the effect of Running

The next step is all the code of LoginPage. cs, with a lot of code, because the layer of ViewModel is not used, haha.

Event Response Code in LoginPage. cs

The User, ValidationModel, and LoginProxy. LoginServiceClient instances are used

DataContext of the front-end UI.

It should be pointed out that btnLogin_Click () has a piece of verification code that looks very bloated, Which is helpless,

The Silverlight Validation mechanism is good, but when you click the [Login] button without entering the UI input box,

This. validationSummary1 does not receive any verification feedback. this. validationSummary1.HasErrors = false,

In this case, only the Binding of each control is verified manually. Therefore, an extension method is provided:

ValidateSource () Extension Method

 

 

In addition, in the use of the LoginProxy. LoginServiceClient instance, determine whether to initialize each WCF asynchronous request before it starts.

To prevent the page from being automatically closed after the timeout time is reached after the page remains unchanged for a long time.

The not found error occurs when a request is sent.

NeedInitializeClient

If you think this is a good habit, you can write it as an extension method, such

NeedInitializeClient

 

The following is the processing code of the WCF asynchronous request.

InitializeClient ()

For simplicity, MessageBox. Show () is used to handle exceptions or prompt messages.

 

 

 

So far, the first phase of this example has been completed. This is a complete example,

The code in LogingPage. cs is also quite clear,

However, some control logic must be mixed in LogingPage. cs, which also leads to the need to further separate these codes,

This is the ViewModel level.

 

Ii. MVVM mode (Model-View-ViewModel Mode)

 

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.