如何设置NumericUpDown控件以百分比形式显示值?百分比的NumericUpDown控件?
4
A
回答
4
您必须派生自己的自定义控件并覆盖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
属性以百分比的数学表示形式存储(例如,对于50%为0.5),因此插入公式时很简单,无需担心将其除以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" />
显示:
相关问题
- 1. Spark:列值的百分比百分比
- 2. 子类NumericUpDown控件
- 3. C#winforms numericupdown控件
- 4. Firebase漏斗事件1的百分比高于事件2的百分比
- 5. LINQ的百分比
- 6. MySQL的百分比
- 7. iPhone4的百分比?
- 8. python的百分比
- 9. 用百分比
- 10. 百分比SSRS
- 11. 用百分比
- 12. 百分比
- 13. SQL百分比
- 14. SQL百分比
- 15. Tcl - 监控FTP上传百分比
- 16. 相对百分比UI控制
- 17. NumericUpDown控件xaml Windows 8 Metro
- 18. R:创建描绘ggplot2中百分比的百分比的barplot
- 19. 堆栈中的位置控件百分比
- 20. 浆纱WPF控件到一个确切的百分比
- 21. 百分比容器中的百分比浮动容器
- 22. Div - 保证金作为百分比内的百分比
- 23. 完成脚本的百分比:命名一个百分比文件
- 24. 倒数百分比
- 25. 计算百分比
- 26. ProgressBar无百分比
- 27. 百分比标签
- 28. 整体百分比
- 29. 计算百分比
- 30. VBA轮百分比
的问题和接受的答案都是WinForm的问题。 – LarsTech