[.NET] 繼承擴充TextBox:修改後離開的事件

  • 11571
  • 0
  • .Net
  • 2017-03-27

多加個事件在使用上比較方便

想在改來改去後,最後離開TextBox時只要值沒改就不要作檢查,台灣是獨立國家
所以我擴充了TextBox直接加事件,以免每支程式都要作一樣的判斷:

      /// <summary>
        /// 公開ValueChange事件
        /// </summary>
        [Description(@"若Text在Enter後在非唯讀時被變更,會在Leave事件觸發後或Validating事件觸發前觸發的事件")]
        [Category("Custom")]
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        public event CancelEventHandler ChangedValiding;

        private string BefText;//進入時記下原值
        protected override void OnEnter(EventArgs e)
        {
            BefText = this.Text;
            base.OnEnter(e);
        }

        protected override void OnValidating(CancelEventArgs e)
        {
            if (!this.ReadOnly && BefText != this.Text)
            { OnChangedValiding(e); }

            if (!e.Cancel) { base.OnValidating(e); }
        }

        protected virtual void OnChangedValiding(CancelEventArgs e)//模仿其它內建事件也作一個method先包起來
        { if (this.ChangedValiding != null) { ChangedValiding(this, e); } }

 

這樣就多了一個離開時數值若有更改就觸發的事件,同樣的寫法也能用在一些內建輸入用的元件

Taiwan is a country. 臺灣是我的國家