×
Namespaces

Variants
Actions
(Difference between revisions)

Implementing numerical InputBox in Windows Phone

From Nokia Developer Wiki
Jump to: navigation, search
symbianyucca (Talk | contribs)
(Symbianyucca -)
 
hamishwillee (Talk | contribs)
m (Hamishwillee -)
(13 intermediate revisions by 5 users not shown)
Line 1: Line 1:
[[Category:Windows Phone 8]][[Category:Location]][[Category:UI]][[Category:Code Snippet]]
+
[[Category:Location on Windows Phone]][[Category:UI on Windows Phone]][[Category:Code Examples]][[Category:Windows Phone 7.5]][[Category:Windows Phone 8]]
In general you can implement numerical input box for WP8 by simply defining the InputScope to be "Number". this would generally give you keyboard only allowing number characters as well as minus sign & decimal separators, however it would not give you options on doing any other filtering.
+
{{Abstract|This article shows how to implement a numerical input box, which handles negative/ positive integers as well as float values, in WP8 applications.}}
 +
{{ArticleMetaData <!-- v1.2 -->
 +
|sourcecode= [https://projects.developer.nokia.com/WP8MapsExamples/browser/AreaSelector/AreaSelector/NumberInputBox.cs NumberInputBox.cs]
 +
|installfile= <!-- Link to installation file (e.g. [[Media:The Installation File.sis]]) -->
 +
|devices=
 +
|sdk= Windows Phone 8.0 SDK
 +
|platform= Windows Phone 8
 +
|devicecompatability= <!-- Compatible devices e.g.: All* (must have internal GPS) -->
 +
|dependencies= <!-- Any other/external dependencies e.g.: Google Maps Api v1.0 -->
 +
|signing=<!-- Signing requirements - empty or one of: Self-Signed, DevCert, Manufacturer -->
 +
|capabilities= <!-- Capabilities required by the article/code example (e.g. Location, NetworkServices. -->
 +
|keywords= <!-- APIs, classes and methods (e.g. QSystemScreenSaver, QList, CBase -->
 +
|language= <!-- Language category code for non-English topics - e.g. Lang-Chinese -->
 +
|translated-by= <!-- [[User:XXXX]] -->
 +
|translated-from-title= <!-- Title only -->
 +
|translated-from-id= <!-- Id of translated revision -->
 +
|review-by= [[User:croozeus]]
 +
|review-timestamp= 20130306
 +
|update-by= <!-- After significant update: [[User:username]]-->
 +
|update-timestamp= <!-- After significant update: YYYYMMDD -->
 +
|creationdate=20130304
 +
|author= [[User:symbianyucca ]]
 +
}}
 +
== Introduction==
 +
In general you can implement numerical {{Icode|InputBox}} for WP8 by simply defining the {{Icode|InputScope}} to be ''Number''. This gives you a keyboard with numerical characters as well as the minus sign and decimal separators. This implementation of an {{Icode|InputBox}} does not give options to do any other filtering.
  
This article is illustrating a bit simplified way on doing input filtering in a way that the input box input can be handled for both negative and positive integer & float numbers. Also simple way on showing the valid range is also illustrated.
+
This article illustrates a simplified way on doing input filtering such that the {{Icode|InputBox}} can be handled for both negative and positive integers as well as float values. This article also illustrates a simple way of showing a valid range. Such an {{Icode|InputBox}} is very useful in certain scenarios - for example while providing a latitude or a longitude as an input, as shown below.  
The example here, has been implemented in several Map examples stored in [http://projects.developer.nokia.com/WP8MapsExamples Windows Phone 8 Maps Examples project].
+
  
Generally to get the input to work as expected, you need to:
+
[[File:Wp8 numberInput.png|800px]]
#  implement NumberInputBox the class
+
#  include the name space in your xaml file
+
#  use the NumberInputBox just as you would use normal textboxe’s
+
  
 +
The example in this article has been implemented in several Map examples available in the [http://projects.developer.nokia.com/WP8MapsExamples Windows Phone 8 Maps Examples project].
  
== implementing the NumberInputBox the class ==
+
Generally, to get the input to work as expected, you need to:
To include new class into a project, you would simply right click the project, select “Add”->”New item” from the pop-up menu and then select “Class” from the list and gibe the class meaningful name.
+
#  Implement {{Icode|NumberInputBox}} the class
As we simply want to make inoutbox, we get it done lot easier by reusing implementations already available, thus we derive the new class from
+
#  Include the namespace in your xaml file
 +
#  Use the {{Icode|NumberInputBox}} just as you would use normal textboxes
 +
 
 +
== Implementing the NumberInputBox class ==
 +
To include new class into a project, you would simply right click the project, select '''Add->New item''' from the pop-up menu and then select '''Class''' from the list and give the class a meaningful name.
 +
 
 +
As we simply want to make {{Icode|InputBox}}, we get it done lot easier by reusing the already available implementations. Thus, we derive a new class from {{Icode|TextBox}} as shown below.
 
<code csharp>
 
<code csharp>
 
public class NumberInputBox : TextBox  
 
public class NumberInputBox : TextBox  
 
</code>
 
</code>
Then to enable different types of input, we define enumeration which is defining the available input types:
+
To enable different types of input, we define an enumeration which accounts for available input types, as shown below.
 
<code csharp>
 
<code csharp>
 
public enum InputType
 
public enum InputType
Line 27: Line 54:
 
}
 
}
 
</code>
 
</code>
Then we define internal variable for which we can set the input type into. Also we have internal variables for limiting the values for valid input, as well as Boolean variable which would be telling whether the current input is inside the defined range.
+
We then define an internal variable for which we can set the input type into. Also, we have internal variables for limiting the values for a valid input, as well as a Boolean variable which indicates whether the current input is in the defined range.
 
<code csharp>
 
<code csharp>
 
public InputType Type { get; set; }
 
public InputType Type { get; set; }
Line 34: Line 61:
 
public bool ValueOk { get; set; }
 
public bool ValueOk { get; set; }
 
</code>
 
</code>
Which after we can then implement the constructor for the class. Inside the constructor, we will need to set the input scope to make sure we get right keyboard for the input, as well as we need to set the callback for the TextChanged event. Which after we simply set default values for the internal variables, so make sure that they are always valid.  
+
 
 +
We can then implement the constructor for the class. Inside the constructor, we will need to set the input scope to make sure we get right keyboard for the input, as well as we need to set the callback for the {{Icode|TextChanged}} event. Which after we simply set default values for the internal variables, so to make sure that they are always valid.  
 
<code csharp>
 
<code csharp>
 
public NumberInputBox(): base()
 
public NumberInputBox(): base()
Line 48: Line 76:
 
}
 
}
 
</code>
 
</code>
Then the actual filtering of the input happens inside the TextChangedEvent function. Inside the function, we simply take the current input, put it through our own parser, and then set it back to the visible text. After setting the value, we do check whether we have max/min values set, and if they are, we check the input range, and use color to indicate whether the value is inside the defined range.
+
Then the actual filtering of the input happens inside the {{Icode|TextChangedEvent}} function. Inside the function, we simply take the current input, put it through our own parser, and then set it back to the visible text. After setting the value, we check whether we have max/min values set, and if they are we check the input range and use colour to indicate whether the value is within the defined range.
 
<code csharp>
 
<code csharp>
 
private void TextChangedEvent(object sender, TextChangedEventArgs e)
 
private void TextChangedEvent(object sender, TextChangedEventArgs e)
Line 74: Line 102:
 
}
 
}
 
</code>
 
</code>
The parsing code is then really simple. It basically takes the whole input buffer, and removes any characters which are not allowed and then returns string which is only having allowed input characters. The buffer is simple looped through in for loop from first character until the last.
+
The parsing code is really simple. It basically takes the whole input buffer and removes any characters which are not allowed. After which it returns the string which is only having allowed input characters. The buffer is simple looped through in for loop from first character until the last.
  
 
In each loop, first in the validations the first character is checked whether it contains minus sign, and this character is only allowed to be the first character, in any other place it will be ignored. Also if only positive input is allowed, then no minus sign is accepted in any position.
 
In each loop, first in the validations the first character is checked whether it contains minus sign, and this character is only allowed to be the first character, in any other place it will be ignored. Also if only positive input is allowed, then no minus sign is accepted in any position.
  
Second check is accepting any digit-characters at any position of the buffer.  
+
The second check is accepting any digit-characters at any position of the buffer.  
  
And if the number input is in float mode, then the last check is allowing the buffer to contain single instance of decimal separator. Note that the decimal separator used inside the code depends on the locale used, the UI default separator might not match the one required by the code, thus, with this check, both dot and comma characters are allowed, but the returned buffer will only contain the decimal separator for the current locale.
+
If the number input is in float mode, then the last check is allowing the buffer to contain single instance of decimal separator. Note that the decimal separator used inside the code depends on the locale used, the UI default separator might not match the one required by the code. Thus, with this check both dot and comma characters are allowed however the returned buffer will only contain the decimal separator for the current locale.
 
<code csharp>
 
<code csharp>
 
String ParseDouble(string input)
 
String ParseDouble(string input)
Line 126: Line 154:
 
}
 
}
 
</code>
 
</code>
== Add NumberInputBox to your XAML ==
+
== Adding NumberInputBox to your XAML ==
First you need to add the namespace to your XAML file, f.ex. if the class is defined under the AreaSelector namespace, then simple add following text into the header section of the XAML file.  
+
First you need to add the namespace to your XAML file. For e.g. if the class is defined under the {{Icode|AreaSelector}} namespace, then simple add following text into the header section of the XAML file.  
 
<code csharp>
 
<code csharp>
 
xmlns:myns="clr-namespace:AreaSelector"  
 
xmlns:myns="clr-namespace:AreaSelector"  
 
</code>
 
</code>
Then to use the control, instead of using textbox tags  you would be using myns:NumberInputBox tags instead. For example if you wish to have input boxes for latitude and  longitude values, you could do it as follows:
+
Then to use the control, instead of using textbox tags  you would be using {{Icode|myns:NumberInputBox}} tags instead. For example, if you wish to have input boxes for latitude and  longitude values, you could do it as follows:
 
<code csharp>
 
<code csharp>
 
<myns:NumberInputBox x:Name="LatitudeBox" Type="Float" MaxValue="90" MinValue="-90"/>
 
<myns:NumberInputBox x:Name="LatitudeBox" Type="Float" MaxValue="90" MinValue="-90"/>
 
<myns:NumberInputBox x:Name="LongittudeBox" Type="Float" MaxValue="180" MinValue="-180"/>
 
<myns:NumberInputBox x:Name="LongittudeBox" Type="Float" MaxValue="180" MinValue="-180"/>
 
</code>
 
</code>
 +
 +
== Summary ==
 +
 +
This article showed how to implement a numerical {{Icode|InputBox}} in WP8 applications. Such an {{Icode|InputBox}} may be useful for accepting input values such as latitude or longitude values.

Revision as of 13:59, 2 July 2013

This article shows how to implement a numerical input box, which handles negative/ positive integers as well as float values, in WP8 applications.

WP Metro Icon UI.png
WP Metro Icon WP8.png
SignpostIcon WP7 70px.png
Article Metadata
Code Example
Source file: NumberInputBox.cs
Tested with
SDK: Windows Phone 8.0 SDK
Compatibility
Platform(s): Windows Phone 8
Windows Phone 8
Windows Phone 7.5
Article
Created: symbianyucca (04 Mar 2013)
Reviewed: croozeus (06 Mar 2013)
Last edited: hamishwillee (02 Jul 2013)

Contents

Introduction

In general you can implement numerical InputBox for WP8 by simply defining the InputScope to be Number. This gives you a keyboard with numerical characters as well as the minus sign and decimal separators. This implementation of an InputBox does not give options to do any other filtering.

This article illustrates a simplified way on doing input filtering such that the InputBox can be handled for both negative and positive integers as well as float values. This article also illustrates a simple way of showing a valid range. Such an InputBox is very useful in certain scenarios - for example while providing a latitude or a longitude as an input, as shown below.

Wp8 numberInput.png

The example in this article has been implemented in several Map examples available in the Windows Phone 8 Maps Examples project.

Generally, to get the input to work as expected, you need to:

  1. Implement NumberInputBox the class
  2. Include the namespace in your xaml file
  3. Use the NumberInputBox just as you would use normal textboxes

Implementing the NumberInputBox class

To include new class into a project, you would simply right click the project, select Add->New item from the pop-up menu and then select Class from the list and give the class a meaningful name.

As we simply want to make InputBox, we get it done lot easier by reusing the already available implementations. Thus, we derive a new class from TextBox as shown below.

public class NumberInputBox : TextBox

To enable different types of input, we define an enumeration which accounts for available input types, as shown below.

public enum InputType
{
Integer = 0,
IntegerPositive = 1,
Float = 2,
FloatPositive = 3,
}

We then define an internal variable for which we can set the input type into. Also, we have internal variables for limiting the values for a valid input, as well as a Boolean variable which indicates whether the current input is in the defined range.

public InputType Type { get; set; }
public int MaxValue { get; set; }
public int MinValue { get; set; }
public bool ValueOk { get; set; }

We can then implement the constructor for the class. Inside the constructor, we will need to set the input scope to make sure we get right keyboard for the input, as well as we need to set the callback for the TextChanged event. Which after we simply set default values for the internal variables, so to make sure that they are always valid.

public NumberInputBox(): base()
{
TextChanged += TextChangedEvent;
this.InputScope = new InputScope()
{
Names = { new InputScopeName() { NameValue = InputScopeNameValue.Number } }
};
this.Type = NumberInputBox.InputType.Integer;
this.MaxValue = this.MinValue = 0;
ValueOk = false;
}

Then the actual filtering of the input happens inside the TextChangedEvent function. Inside the function, we simply take the current input, put it through our own parser, and then set it back to the visible text. After setting the value, we check whether we have max/min values set, and if they are we check the input range and use colour to indicate whether the value is within the defined range.

private void TextChangedEvent(object sender, TextChangedEventArgs e)
{
this.Text = ParseDouble(this.Text);
this.SelectionStart = this.Text.Length;
 
if (this.MaxValue != this.MinValue)
{
double d;
if (double.TryParse(this.Text, out d))
{
if (d < this.MinValue || d > this.MaxValue)
{
this.ValueOk = false;
this.Foreground = new SolidColorBrush(Colors.Red);
}
else
{
this.ValueOk = true;
this.Foreground = new SolidColorBrush(Colors.Black);
}
}
}
}

The parsing code is really simple. It basically takes the whole input buffer and removes any characters which are not allowed. After which it returns the string which is only having allowed input characters. The buffer is simple looped through in for loop from first character until the last.

In each loop, first in the validations the first character is checked whether it contains minus sign, and this character is only allowed to be the first character, in any other place it will be ignored. Also if only positive input is allowed, then no minus sign is accepted in any position.

The second check is accepting any digit-characters at any position of the buffer.

If the number input is in float mode, then the last check is allowing the buffer to contain single instance of decimal separator. Note that the decimal separator used inside the code depends on the locale used, the UI default separator might not match the one required by the code. Thus, with this check both dot and comma characters are allowed however the returned buffer will only contain the decimal separator for the current locale.

String ParseDouble(string input)
{
if (input.Length > 0)
{
String outBut = "";
bool foundSeparator = false;
 
for (int i = 0; i < input.Length; i++)
{
if ((this.Type == NumberInputBox.InputType.Integer
|| this.Type == NumberInputBox.InputType.Float)
&& ((i == 0) && input[0] == '-'))
{
outBut = outBut + input[i];
}
else if ((input[i] >= '0' && input[i] <= '9'))
{
outBut = outBut + input[i];
}
else if (this.Type == NumberInputBox.InputType.Float
|| this.Type == NumberInputBox.InputType.FloatPositive)
{
if (foundSeparator == false)
{
string Sepa = CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator;
if (Sepa.Length > 0)
{
if (Sepa[0] == input[i] || '.' == input[i] || ',' == input[i])
{
outBut = outBut + Sepa[0];
foundSeparator = true;
}
}
}
}
}
return outBut;
}
else
{
return "";
}
}

Adding NumberInputBox to your XAML

First you need to add the namespace to your XAML file. For e.g. if the class is defined under the AreaSelector namespace, then simple add following text into the header section of the XAML file.

xmlns:myns="clr-namespace:AreaSelector"

Then to use the control, instead of using textbox tags you would be using myns:NumberInputBox tags instead. For example, if you wish to have input boxes for latitude and longitude values, you could do it as follows:

<myns:NumberInputBox x:Name="LatitudeBox" Type="Float" MaxValue="90" MinValue="-90"/>
<myns:NumberInputBox x:Name="LongittudeBox" Type="Float" MaxValue="180" MinValue="-180"/>

Summary

This article showed how to implement a numerical InputBox in WP8 applications. Such an InputBox may be useful for accepting input values such as latitude or longitude values.

223 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×