wpf 中自定义控件及其使用

主要有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"/>

  

原文地址:https://www.cnblogs.com/EasyInvoice/p/5595655.html