如何設置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