百分比的NumericUpDown控件?

4
如何将NumericUpDown控件设置为以百分比形式显示值?
2个回答

6
你需要派生自己的自定义控件并重写UpdateEditText()方法。与此同时,让我们重写默认的MinimumMaximumIncrement属性值,使它们更加友好地处理百分比。
我们还需要重写基本的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

我们可以通过添加一个属性来稍微扩展类的范围,以此设置我们想在设计时使用的数字显示格式,这样我们就能支持将值以货币的形式显示。
上述代码虽然紧凑且专门针对百分比,但它利用了现有的属性。 属性以百分数的数学表示方式存储(例如,50%的值为0.5),因此可以简单地插入到公式中,无需担心除以100。

2
这个问题的快速简单答案是:使用Extended WPF Toolkit中的DecimalUpDown,而不是NumericUpDown(需要注意的是,NumericUpDown也被列为过时)。然后你只需要在XAML中设置Maximum="1" Minimum="0.01" Increment="0.01" FormatString="P0"。我假设这个问题是关于Extended WPF Toolkit的,因为上面的答案就是针对它的。
例如:
<xctk:DecimalUpDown Maximum="1" Minimum="0.01" Value="0.01" Increment="0.01" FormatString="P0" />

显示:

DecimalUpDown Example


这个问题和被接受的答案都是WinForm问题。 - LarsTech

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接