如何设置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属性. Value属性存储为百分比的数学表示(例如,50为50%),因此插入公式很简单,而不必担心除以100.