WPF Custom TextBox with Decimal Formatting

做~自己de王妃 提交于 2019-12-01 23:11:17

I have written a custom control which will have dependency property called ActualText. Bind your value into that ActualText property and manipulated the Text property of the textbox during the gotfocus and lostfocus event. Also validated for decimal number in the PreviewTextInput event. refer the below code.

 class TextBoxEx:TextBox
{
    public string ActualText
    {
        get { return (string)GetValue(ActualTextProperty); }
        set { SetValue(ActualTextProperty, value); }
    }

    // Using a DependencyProperty as the backing store for ActualText.  This enables animation, styling, binding, etc...
    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;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!