I am new to WPF. I have a requirement that I need to develop a custom textbox control which should support the functionality like:
Should accept only decimal values.
Should round off to 3 decimal places when assigned a value through code or by the user.
Should show the full value(without formatting) on focus.
Eg:
If 2.21457 is assigned to textbox(by code or by user), it should display 2.215. When user clicks in it to edit it, it must show the full value 2.21457. After the user edits the value to 5.42235 and tabs out, it should again round off to 5.422.
Tried it without success. So need some help on it. Thanks in advance for the help.
Thanks
[Edit - Kenneth Haugland]
Hey, Sorry for the late reply. I tried creating a custom control. It does contain some drawbacks but working on it.
class TextBoxEx:TextBox
{
public string ActualText
{
get { return (string)GetValue(ActualTextProperty); }
set { SetValue(ActualTextProperty, value); }
}
public static readonly DependencyProperty ActualTextProperty =
DependencyProperty.Register("ActualText", typeof(string), typeof(TextBoxEx), new PropertyMetadata(string.Empty, OnActualTextChanged));
private static void OnActualTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TextBox tx = d as TextBox;
tx.Text = (string)e.NewValue;
string str = tx.Text;
double dbl = Convert.ToDouble(str);
str = string.Format("{0:0.###}", dbl);
tx.Text = str;
}
public TextBoxEx()
{
this.GotFocus += TextBoxEx_GotFocus;
this.LostFocus += TextBoxEx_LostFocus;
this.PreviewTextInput += TextBoxEx_PreviewTextInput;
}
void TextBoxEx_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
{
decimal d;
if(!decimal.TryParse(e.Text,out d))
{
e.Handled = true;
}
}
void TextBoxEx_LostFocus(object sender, System.Windows.RoutedEventArgs e)
{
ConvertText();
}
void TextBoxEx_GotFocus(object sender, System.Windows.RoutedEventArgs e)
{
this.Text = ActualText;
}
private void ConvertText()
{
string str = this.Text;
ActualText = str;
double dbl = Convert.ToDouble(str);
str = string.Format("{0:0.###}", dbl);
this.Text = str;
}
}
[/Edit]