具有十进制格式的WPF自定义文本框

时间:2015-02-21 07:23:06

标签: wpf textbox format decimal custom-controls

我是WPF的新手。 我要求我需要开发一个自定义文本框控件,它应该支持以下功能:

  1. 只接受小数值。

  2. 通过代码或用户分配值时,应舍入到3位小数。

  3. 应在焦点上显示完整值(无格式化)。

  4. 例如:

    如果将2.21457分配给文本框(按代码或按用户分配),则应显示2.215。当用户点击它进行编辑时,它必须显示完整值2.21457。 用户将值编辑为5.42235并标签后,它应再次舍入到5.422。

    尝试没有成功。所以需要一些帮助。 在此先感谢您的帮助。

    由于

1 个答案:

答案 0 :(得分:1)

我编写了一个自定义控件,它将具有名为ActualText的依赖项属性。将您的值绑定到ActualText属性,并在gotfocus和lostfocus事件期间操纵文本框的Text属性。还在PreviewTextInput事件中验证十进制数。请参考以下代码。

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