using System;
namespace Gwen.Control
{
///
/// Numeric text box - accepts only float numbers.
///
public class TextBoxNumeric : TextBox
{
///
/// Current numeric value.
///
protected float m_Value;
///
/// Initializes a new instance of the class.
///
/// Parent control.
public TextBoxNumeric(Base parent)
: base(parent)
{
SetText("0", false);
}
protected virtual bool IsTextAllowed(String str)
{
if (str == "" || str == "-")
return true; // annoying if single - is not allowed
float d;
return float.TryParse(str, out d);
}
///
/// Determines whether the control can insert text at a given cursor position.
///
/// Text to check.
/// Cursor position.
/// True if allowed.
protected override bool IsTextAllowed(String text, int position)
{
String newText = Text.Insert(position, text);
return IsTextAllowed(newText);
}
///
/// Current numerical value.
///
public virtual float Value
{
get { return m_Value; }
set
{
m_Value = value;
Text = value.ToString();
}
}
// text -> value
///
/// Handler for text changed event.
///
protected override void OnTextChanged()
{
if (String.IsNullOrEmpty(Text) || Text == "-")
{
m_Value = 0;
//SetText("0");
}
else
m_Value = float.Parse(Text);
base.OnTextChanged();
}
///
/// Sets the control text.
///
/// Text to set.
/// Determines whether to invoke "text changed" event.
public override void SetText(string str, bool doEvents = true)
{
if (IsTextAllowed(str))
base.SetText(str, doEvents);
}
}
}