Axarydax
Axarydax

Reputation: 16623

Replace parent class event with my own

I'd like to implement a new version of TextBox, let's call it FunkyTextBox that will raise TextChanged event only after every third text change.

If I only wanted to raise another event for this, let's call it FunkyTextChanged, the implementation is straightforward:

class FunkyTextBox : TextBox
{
    int counter = 0;
    int MAX_CHANGES = 3;
    public event EventHandler FunkyTextChanged;

    public FunkyTextBox()
    {
        this.TextChanged += (s, e) =>
        {
            if (++counter < MAX_CHANGES)
                return;
            counter = 0;
            if (FunkyTextChanged != null)
                FunkyTextChanged(this, null);
        };
    }
}

But this approach has one disadvantage - user would assume to use TextChanged, which is the parent's version that is raised after single change and wouldn't think to subscribe to FunkyTextChanged event.

Is it possible to use TextChanged event for this? To somehow hide parent's TextChnaged from users of FunkyTextBox and replace it with its own?

Upvotes: 4

Views: 84

Answers (2)

jbl
jbl

Reputation: 15423

I would go for something like :

    class FunkyTextBox : TextBox
    {
        int counter = 0;
        int MAX_CHANGES = 3;

        public FunkyTextBox()
        {
        }

        protected override void OnTextChanged(EventArgs e)
        {
            if (++counter < MAX_CHANGES)
                return;
            counter = 0;
            base.OnTextChanged(e);
        }
    }

Upvotes: 3

bash.d
bash.d

Reputation: 13217

Simply override the OnTextChanged protected method with your implementation.

protected override void OnTextChanged(TextChangedEventArgs e){
  // your code here
}

As this method is virtual, if you use your custom textbox, this method should be called.

See here for WinForms and here for WPF.

Upvotes: 2

Related Questions