gpt4 book ai didi

.net - 百分比的 NumericUpDown 控件?

转载 作者:行者123 更新时间:2023-12-03 18:22:21 24 4
gpt4 key购买 nike

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

最佳答案

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

我们还需要覆盖基础 ParseEditText()将用户生成的输入解释为百分比(除以 100)的方法,因为用户希望输入 80代表80% (并且 Decimal 解析器需要忽略百分比符号)。

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属性(property)。 Value属性存储为百分比的数学表示(例如,0.5 表示 50%),因此可以轻松插入公式而无需担心除以 100。

关于.net - 百分比的 NumericUpDown 控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14722634/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com