Windows Universal app –tip Calculator

Source: Internet
Author: User

Statement

The following is from Bob Tabor's course "Windows Phone 8.1 Development for Absolute beginners" with the link address:/http Www.microsoftvirtualacademy.com/training-courses/windows-phone-8-1-development-for-absolute-beginners

Objective

The Universal app is a cross-platform application development that currently targets windows and Windows Phone devices. Here, we will design and complete a Universal Tip Calculator application that can be deployed on a Windows Phone phone or on a Windows device.

1. Application background

Tip Calculator, this app is inspired by eating out, foreigners generally have to give waiters the habit of tipping, and how much the tip should be paid according to the service quality of the waiter. This application design tip rule is this, the service generally pay 10%, better service 18%, perfect service 25%.

2. Project Creation

First, we need to create an application, choose Templates > Visual C # > Store apps > Universal apps, select the Blank app (Universal apps), named Tipcalculat Oruniversal, click OK.

After the project was created, we looked at the solution browser and found three items starting with the project name: Windows, Windows Phone, and shared.

The project for Windows and Windows Phone differs in the XAML layout because some of the controls differ on different platforms. If it is a class and a method that can be used on two platforms, we can put it into the share project. In this app, put the Tip.cs file in a shared project and reference it in the project for Windows and Windows Phone.

3. Shared project design

In the shared project, right-click to add a new file:

In the dialog box, select Class, Name Tip.cs, and click Add.

Add the following code to the Tip.cs file, note that two points, first of all, set the Tip class to be public. Second, create three properties, Billamount, Tipamount, and TotalAmount

public class Tip

{

public string Billamount {get; set;}

public string Tipamount {get; set;}

public string TotalAmount {get; set;}

}

Next, you set the constructor to initialize each property value to an empty string.

Public Tip ()

{

This. Billamount = String.Empty;

This. Tipamount = String.Empty;

This. TotalAmount = String.Empty;

}

Next, create a method to calculate the tip:

public void Calculatetip (String originalamount, double tippercentage)

{

Double billamount = 0.0;

Double tipamount = 0.0;

Double totalamount = 0.0;

if (double. TryParse (Originalamount.replace (' $ ', '), out Billamount))

{

Tipamount = Billamount * tippercentage;

TotalAmount = Billamount + tipamount;

}

This. Billamount = String.Format ("{0:c}", Billamount);

This. Tipamount = String.Format ("{0:c}", Tipamount);

This. TotalAmount = String.Format ("{0:c}", TotalAmount);

}

In this method, the two key elements of originalamount and Tippercentage are passed in as parameters, which are stored in the public properties of the class after the tip and the total price are calculated. Note that we are using double here. The TryParse () method returns an exception if the user enters a value that is not a number.

4. Windows Phone project design

Now, let's look at the Windows Phone project and add the following line definition to the gird of the MainPage.xaml file:

<Grid.RowDefinitions>

<rowdefinition height= "/>"

<rowdefinition height= "/>"

<rowdefinition height= "*"/>

</Grid.RowDefinitions>

The first and second lines are used to display the application name and application hints, such as:

<textblock margin= "20, 0, 20, 0"

grid.row= "0"

Style= "{StaticResource Titletextblockstyle}" >

Tip Calculator

</TextBlock>

<textblock margin= "20, 0, 20, 0"

grid.row= "1"

Style= "{StaticResource Titletextblockstyle}"

Fontsize= ">"

Enter the Bill Amount

</TextBlock>

Next, we add a StackPanel to the third line, occupying the entire remaining space. Add the following controls to StackPanel:

<stackpanel name= "myStackPanel" grid.row= "2" margin= "0, 0" >

<textblock horizontalalignment= "left"

Textwrapping= "Wrap"

text= "Bill Amount"

Fontsize= "/>"

<textbox name= "Billamounttextbox"

text= "$0.00"

Textalignment= "Right"

Horizontalalignment= "left"

Textwrapping= "Wrap"

Verticalalignment= "Top"

Inputscope= "Number"

Width= "100"

Fontsize= "24"

Lostfocus= "Amounttextbox_lostfocus"

Textchanged= "Billamounttextbox_textchanged"

gotfocus= "Amounttextbox_gotfocus"/>

</StackPanel>

In the above code, Billamounttextbox allows the user to enter the total price on the bill, which is the basis for calculating the tip. Next, add a TextBlock and a series of radiobuttons that let the user choose the quality of the service to calculate the tip:

<textblock horizontalalignment= "left"

Textwrapping= "Wrap"

Text= "Percent to Tip:"

Verticalalignment= "Top"

Fontsize= "24"

margin= "0,20,0,0"/>

<radiobutton content= "10%-horrible Service"

Tag= "0.1"

Groupname= "Percentradio"

click= "Radiobutton_click"/>

<radiobutton content= "18%-acceptable Service"

Tag= "0.18"

Groupname= "Percentradio"

Ischecked= "True"

click= "Radiobutton_click"/>

<radiobutton content= "25%-Great Service"

tag= "0.25"

Groupname= "Percentradio"

click= "Radiobutton_click"/>

Note that I used the Tag property of RadioButton to indicate the percentage of tips that were calculated. In this case, I can get the tag property directly and calculate the tip without using the switch statement. 0.1 indicates that 10%,0.18 represents 18%,0.25 25%.

Next, we need to show the results of the tip calculation, adding the following two TextBlock:

<textblock horizontalalignment= "left"

Textwrapping= "Wrap"

Text= "Amount to Tip:"

Fontsize= "24"

margin= "0,20,0,0"/>

<textblock name= "Amounttotiptextblock"

Horizontalalignment= "left"

Textwrapping= "Wrap"

Verticalalignment= "Top"

text= "$0.00"

Fontsize= "/>"

Finally, the total price containing the tip and the bill is shown, which is the last rate I paid by credit card:

<textblock horizontalalignment= "left"

Textwrapping= "Wrap"

Verticalalignment= "Top"

Text= "Total Bill:"

Fontsize= "24"

margin= "0,20,0,0"/>

<textblock x:name= "Totaltextblock"

Horizontalalignment= "left"

Textwrapping= "Wrap"

Verticalalignment= "Top"

text= "$0.00"

Fontsize= "/>"

The Billamounttextbox and RadioButton controls contain a series of events that we need to handle. For example, when a user clicks Billamounttextbox to enter a bill, we need to first empty the existing content. After the user edits the number, we need to calculate the tip and the total price. When the user's focus moves out of billamounttextbox, we add the necessary dollar symbol to the number. Next, we create the corresponding event handler by right-clicking on the corresponding event in the XAML editor and choosing go To Definition.

In the corresponding CS file, the event handler functions created are as follows

In the background code, we create an object of the Tip class and create an instance of the object in the MainPage constructor:

In addition, in the Performcalculation () method, we call the Tip class's Calculatetip method to calculate the required tip and general bill.

private void Performcalculation ()

{

var selectedradio = mystackpanel.children.oftype<radiobutton> (). FirstOrDefault (r = r.ischecked = = true);

Tip. Calculatetip (Billamounttextbox.text, double. Parse (SelectedRadio.Tag.ToString ()));

Amounttotiptextblock.text = tip. Tipamount;

Totaltextblock.text = tip. TotalAmount;

}

The first line of the method is to use a LINQ statement to check the user's choice of RadioButton; The advantage of this approach is that by adding a new RadioButton control, we don't need to add new code to complete this judgment, but it's different if you use the switch statement.

After you have obtained the user-selected RadioButton, you can call the Tip class's Calculatetip method for calculation. Finally, the computed results are assigned to the corresponding control display.

Also, when do you need to execute this performcalculation function? First, when the user enters a new bill, that is when the event is triggered, followed by the user choosing a different tip ratio, when the (Radiobutton_click) event is triggered.

private void Billamounttextbox_textchanged (object sender, Textchangedeventargs e)

{

Performcalculation ();

}

private void Radiobutton_click (object sender, RoutedEventArgs e)

{

Performcalculation ();

}

In this way, we can debug the application. But there are still some inconveniences. For example, when I click Bill Amount TextBox control to enter content, the control should automatically empty the last entry I entered, rather than manually clearing it by myself.

Second, after entering the finished content, I want to precede with the dollar symbol.

To achieve these two functions, we can do this in the following way.

First, when the amount textbox gets the focus, let's clear its contents:

private void Amounttextbox_gotfocus (object sender, RoutedEventArgs e)

{

Billamounttextbox.text = "";

}

Now, once again the debugger, you will find that when you click on the textbox, it will ever be emptied.

Second, in order to add a dollar character to the input, I call the Tip class's Calculatetip () method when it loses focus,

private void Amounttextbox_lostfocus (object sender, RoutedEventArgs e)

{

Billamounttextbox.text = tip. Billamount;

}

The debug results are as follows:

Note that the default is the Windows project as the start up project, and we want to modify it to a Windows Phone project as a startup project, right-click on the Windows Phone project and select "Set as Start Up project". That's all you can do.

5. Windows project Design

For the sake of testing convenience, I re-set the Windows project to start up project, the same way as above, next, open the Windows project's MainPage.xaml file, preview the following:

Let's look at how easy it is to complete the Windows project based on the existing phone interface design. So, first I copy the page layout code in the MainPage.xaml in the phone, you can see the following effect:

While there is a lot of free space on our interface, we can see that our XAML controls in the phone are also available here.

In addition to the XAML code, the background code also needs to be modified, mainly related event handlers. Note that the background code is handled exactly the same as the example above.

When we finish, we click Simulator and start Debugging. The application interface is as follows:

So, through the content of this project, we found that in this universal app, the exact same XAML page layout code was used and a tip class was used. Of course, if for the sake of beauty, we can of course stretch the Windows version control to be more suitable for the screen. Therefore, when you create an application, I recommend that you put common logic, rules, data acquisition, and processing into a shared project, and then reference it in Windows and Windows Phone programs. This allows us to make the application available on several different platforms.

Reference Links:

Windows Phone 8.1 development for Absolute Beginners

Bob Tabor (Microsoft MVP)

• Links: Http://www.microsoftvirtualacademy.com/training-courses/windows-phone-8-1-development-for-absolute-beginners

• Source Code Link: http://aka.ms/absolutebeginnerwp81

Windows Universal app –tip Calculator

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.