Reputation: 219
I would like to know if I bind the TextChanged
event handler to a TextBox
control, then how can I ensure that won't be allowed to bind this event handler again?
Upvotes: 0
Views: 1609
Reputation: 1653
You can actually use a hack.
private TextBox txtChanging;
public event Action TextBoxTextChanged;
private OnTextBoxChanged( object sender, EventArgs args )
{
if( TextBoxTextChanged != null )
TextBoxTextChanged();
}
txtChanging.TextChanged += OnTextBoxChanged;
Ensure that NO OTHER METHOD is bound to TextChanged event of the text box
Bound all your main payload text changed handlers to your new custom event instead of text box textchanged event directly
TextBoxTextChanged += txtChanged_TextChnaged;
All that paperwork is because events actually provide a lot of information, but only to the methods inside the class where they are defined.
You can check bound delegates with
TextBoxTextChanged.GetInvocationList()
and their count with
TextBoxTextChanged.GetInvocationList().Count() //(C# 4.0/LINQ)
or just count them through foreach.
Upvotes: 0
Reputation: 12314
You can bind it programatically as many times as you'd like. If you want to prevent this you can use a List<object> to keep references in, for example:
private List gotRefs = new List();
public void MyMethod()
{
if (!gotRefs.Contains(txtTextBox1)) {
txtTextBox1.TextChanged += txtTextBox1_TextChanged;
gotRefs.Add(txtTextBox1);
}
}
Upvotes: 0
Reputation: 244812
You can't ensure that. You would theoretically be allowed to bind the same event handler to a textbox (or other control) more than once. The only thing that events allow you to do is add a handler and remove a handler—there's no additional means provided to check for existing subscribers. If you don't believe me, Jon Skeet provides the authoritative answer here, and in his article on events.
If you need to ensure that you don't accidentally subscribe a control to the same event twice, you'll need to keep track of it yourself. Honestly, you should never end up in a situation where you don't know what event handlers are subscribed. Not only does this reflect sloppy design, but it probably also means that you aren't taking care to remove your event handlers when they are no longer necessary.
A possible solution is provided in the answers to this question, but I caution you from using something like this blindly. As others have argued, this code is something of an anti-pattern.
Upvotes: 3