Tagged: decimal point

Single Decimal Point

Among the first issues I encountered when working on a windows phone application was the simple, plain textbox. This apparently friendly control has a dark side in a particular use case. When the InputScope is set to Numerical, it allows entering multiple decimal points.

before

In my case, I didn’t needed this “feature”. The best solution I could find to limit the decimal point to one, or none, was to develop an attached behavior.

You can find the complete solution here.

Below is the behavior’s structure:

BehaviorStructure

The attached property IsDecimalPointAllowed will set the behavior to allow one or zero decimal points in the input.

public static readonly DependencyProperty IsDecimalPointAllowedProperty =
DependencyProperty.RegisterAttached("IsDecimalPointAllowed", typeof(bool?), typeof(DecimaPointBehavior), new PropertyMetadata(null, OnIsDecimalPointAllowedChanged));

public static bool? GetIsDecimalPointAllowed(DependencyObject obj)
{
  return (bool?)obj.GetValue(IsDecimalPointAllowedProperty);
}

public static void SetIsDecimalPointAllowed(DependencyObject obj, bool? value)
{
  obj.SetValue(IsDecimalPointAllowedProperty, value);
}

When the attached property is set to true or false, the value of the regex is established.

  • For limiting the input to allow only one decimal point:
"^([0-9]+)?([,|\.])?([0-9]+)?$"
  • For limiting the input to block any decimal point:
"^([0-9]+)?$"

 

When the text inside the textbox changes, the new value is matched against the established regex:

private static void textBox_TextChanged(object sender, TextChangedEventArgs e)
{
 var textBox = (TextBox)sender;
 var match = Regex.Match(textBox.Text, regex);
 if (!match.Success)
 {
   textBox.Text = textBox.Text.Remove(textBox.Text.Length - 1);
   textBox.Select(textBox.Text.Length, 0);
 }
}

 

For no decimal point allowed, set the IsDecimalPointAllowed to false:

<TextBox Height="100"
InputScope="Number"
behaviors:DecimaPointBehavior.IsDecimalPointAllowed="False" />;

NoDecimalPoint

For one decimal point allowed, set the IsDecimalPointAllowed to true:

<TextBox Height="100"
InputScope="Number"
behaviors:DecimaPointBehavior.IsDecimalPointAllowed="True" />;

OneDecimalPoint

Advertisement