wpf 中自定义控件及其使用

≯℡__Kan透↙ 提交于 2019-12-09 03:31:17

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!