WPF Custom TextBox with Decimal Formatting

十年热恋 提交于 2019-12-02 06:23:15

问题


I am new to WPF. I have a requirement that I need to develop a custom textbox control which should support the functionality like:

  1. Should accept only decimal values.

  2. Should round off to 3 decimal places when assigned a value through code or by the user.

  3. 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


回答1:


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;
    }
}


来源:https://stackoverflow.com/questions/28643298/wpf-custom-textbox-with-decimal-formatting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!