【问题标题】:NumericUpDown control for Percentages?百分比的 NumericUpDown 控件?
【发布时间】:2013-01-21 06:30:41
【问题描述】:

如何设置 NumericUpDown 控件以将值显示为百分比?

【问题讨论】:

    标签: .net vb.net winforms controls numericupdown


    【解决方案1】:

    您必须派生自己的自定义控件并覆盖UpdateEditText() 方法。在此过程中,让我们覆盖默认的 Minimum、Maximum 和 Increment 属性值,以便对百分比更友好。

    我们还需要重写基本的 ParseEditText() 方法来将用户生成的输入解释为百分比(除以 100),因为用户希望输入 80 来表示 80%(以及十进制解析器需要忽略百分号)。

    Public Class PercentUpDown
        Inherits NumericUpDown
    
        Private Shared ReadOnly DefaultValue As New [Decimal](0.0)      ' 0%
        Private Shared ReadOnly DefaultMinimum As New [Decimal](0.0)    ' 0%
        Private Shared ReadOnly DefaultMaximum As New [Decimal](1.0)    ' 100%
        Private Shared ReadOnly DefaultIncrement As New [Decimal](0.01) ' 1%
    
        Public Sub New()
            Value = DefaultValue
            Minimum = DefaultMinimum
            Maximum = DefaultMaximum
            Increment = DefaultIncrement
        End Sub
    
        Protected Overrides Sub UpdateEditText()
            If UserEdit Then
                ParseEditText()
            End If
    
            Text = Value.ToString(String.Format("p{0}", DecimalPlaces))
        End Sub
    
        Protected Shadows Sub ParseEditText()
            Debug.Assert(UserEdit = True, "ParseEditText() - UserEdit == false")
    
            Try
                If Not String.IsNullOrWhiteSpace(Text) AndAlso _
                   Not (Text.Length = 1 AndAlso Text.Equals("-")) Then
    
                    Value = Constrain(Decimal.Parse(Text.Replace("%", String.Empty), NumberStyles.Any, CultureInfo.CurrentCulture) / 100)
    
                End If
            Catch ex As Exception
                ' Leave value as it is
            Finally
                UserEdit = False
            End Try
        End Sub
    
        Private Function Constrain(origValue As [Decimal]) As [Decimal]
            Debug.Assert(Minimum <= Maximum, "minimum > maximum")
    
            If origValue < Minimum Then Return Minimum
            If origValue > Maximum Then Return Maximum
    
            Return origValue
        End Function
    
    End Class
    

    我们可以通过添加TextFormat 属性来稍微扩展类的范围,我们可以在其中设置我们想在设计时使用的numeric display format,这样我们就可以支持将值显示为货币,例如。

    不过,上面的代码非常简洁,并且专门针对百分比,利用了现有的DecimalPlaces 属性。 Value 属性存储为百分比的数学表示形式(例如,0.5 表示 50%),因此插入公式很简单,无需担心除以 100。

    【讨论】:

      【解决方案2】:

      快速简单地回答这个问题:使用扩展 WPF 工具包中的 DecimalUpDown,而不是 NumericUpDown(应该注意,NumericUpDown 也被列为过时)。然后,您需要做的就是在 XAML 中设置 Maximum="1" Minimum="0.01" Increment="0.01" FormatString="P0"。我假设这个问题是关于扩展 WPF 工具包的,因为上面的答案是针对它的。

      例子:

      <xctk:DecimalUpDown Maximum="1" Minimum="0.01" Value="0.01" Increment="0.01" FormatString="P0" />
      

      显示:

      【讨论】:

      • 问题和接受的答案都是 WinForm 问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多