主要有3個步驟:
1. 首先創建一個自定義的控件,該控件繼承 TextBox
namespace EzIntePark.Presentation.Common { /// <summary> /// 數字框,繼承文本框,僅限數字輸入,擴展 Value(decimal) /// </summary> public class ExNumericBox:TextBox { #region Dependency properties public int Digits { get { return (int)GetValue(DigitsProperty); } set { SetValue(DigitsProperty, value); } } public static readonly DependencyProperty DigitsProperty = DependencyProperty.Register("Digits", typeof(int), typeof(ExNumericBox), new PropertyMetadata(2)); public decimal Value { get { return (decimal)GetValue(ValueProperty); } set { SetValue(ValueProperty,value); } } public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(decimal), typeof(ExNumericBox), new PropertyMetadata(decimal.Zero)); #endregion public ExNumericBox() :base() { this.VerticalContentAlignment = VerticalAlignment.Center; this.TextChanged += new TextChangedEventHandler(NumericBox_TextChanged); } private string backupString = ""; /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void NumericBox_TextChanged(object sender, TextChangedEventArgs e) { TextBox tb = (TextBox)sender; string temp = tb.Text.Trim(); if (!isDecimal(temp)) {//revert string tb.Text = backupString; tb.Select(backupString.Length, 0); return; } decimal tempvalue = 0; Decimal.TryParse(temp, out tempvalue); backupString = temp; Value = tempvalue; } /// <summary> /// 是否數字 /// </summary> /// <param name="source"></param> /// <returns></returns> bool isDecimal(string source) { foreach (char item in source) { if ((item < '0' || item > '9')) { if (Digits == 0) return false; if (Digits != 0 && item != '.') return false; } } return true; } } }
2. window 或 usercontrol 類中要使用該控件時先引入命名空間,如:
xmlns:Common="clr-namespace:EzIntePark.Presentation.Common"
3. 使用該控件
<Common:ExNumericBox x:Name="tbFirstCost" HorizontalAlignment="Left" Height="22" Margin="38,4,0,4" TextWrapping="Wrap" VerticalAlignment="Center" Width="50" VerticalContentAlignment="Center" Grid.Column="1"/>