You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

139 lines
4.1 KiB

using System;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
namespace Gumming
{
public class FloatBox : TextBox
{
#region MaxValue
public static readonly DependencyProperty MaxValueProperty =
DependencyProperty.Register("MaxValue", typeof(Decimal), typeof(FloatBox),
new PropertyMetadata(100000000m, OnMaxValueChanged,
CoerceMaxValue));
public Decimal MaxValue
{
get { return (Decimal)GetValue(MaxValueProperty); }
set { SetValue(MaxValueProperty, value); }
}
private static void OnMaxValueChanged(DependencyObject element,
DependencyPropertyChangedEventArgs e)
{
var control = (FloatBox)element;
var maxValue = (Decimal)e.NewValue;
}
private static object CoerceMaxValue(DependencyObject element, Object baseValue)
{
var maxValue = (Decimal)baseValue;
if (maxValue == Decimal.MaxValue)
{
return DependencyProperty.UnsetValue;
}
return maxValue;
}
#endregion
#region Constructors
/*
* The default constructor
*/
public FloatBox()
{
TextChanged += new TextChangedEventHandler(OnTextChanged);
KeyDown += new KeyEventHandler(OnKeyDown);
}
#endregion
#region Properties
new public String Text
{
get { return base.Text; }
set
{
base.Text = LeaveOnlyNumbers(value);
}
}
#endregion
#region Functions
private bool IsNumberKey(Key inKey)
{
if (inKey == System.Windows.Input.Key.OemPeriod)
{
return true;
}
if (inKey == System.Windows.Input.Key.Decimal)
{
return true;
}
if ((inKey < Key.D0 || inKey > Key.D9) && inKey != Key.OemMinus)
{
if (inKey < Key.NumPad0 || inKey > Key.NumPad9)
{
return false;
}
}
return true;
}
private bool IsDelOrBackspaceOrTabKey(Key inKey)
{
return inKey == Key.Delete || inKey == Key.Back || inKey == Key.Tab;
}
private string LeaveOnlyNumbers(String inString)
{
String tmp = inString;
foreach (char c in inString.ToCharArray())
{
if (!System.Text.RegularExpressions.Regex.IsMatch(c.ToString(), @"^\+?(:?(:?\d+\.\d+)|(:?\d+))|(-?\d+)(\.\d+)?$") && c != '.' && c != '-')
{
tmp = tmp.Replace(c.ToString(), "");
}
}
if (tmp.Count(x => x == '.') > 1)
{
int firstdot = tmp.IndexOf('.');
string header = tmp.Substring(0, firstdot + 1);
string strEnd = tmp.Substring(firstdot + 1);
tmp = header + strEnd.Replace(".", "");
}
return tmp;
}
#endregion
#region Event Functions
protected void OnKeyDown(object sender, KeyEventArgs e)
{
e.Handled = !IsNumberKey(e.Key) && !IsDelOrBackspaceOrTabKey(e.Key);
}
protected void OnTextChanged(object sender, TextChangedEventArgs e)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(Text, @"^\+?(:?(:?\d+\.\d+)|(:?\d+))|(-?\d+)(\.\d+)?$"))
{
base.Text = LeaveOnlyNumbers(Text);
}
decimal value = 0;
decimal.TryParse(Text, out value);
if (value > MaxValue)
{
base.Text = MaxValue.ToString();
}
this.Select(this.Text.Length, 0);
}
#endregion
}
}