I’m creating custom control that contain multiple parts. Inside template creation I’m subscribing for different events like so:
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
this.partAreaCode = this.GetTemplateChild(PartAreaCode) as TextBox;
this.partExchange = this.GetTemplateChild(PartExchange) as TextBox;
this.partSubscriber = this.GetTemplateChild(PartSubscriber) as TextBox;
if (this.partAreaCode == null || this.partExchange == null || this.partSubscriber == null)
{
throw new NullReferenceException("Template part(s) not available");
}
this.partAreaCode.KeyDown += this.AreaKeyDown;
this.partAreaCode.TextChanged += this.AreaTextChanged;
this.partExchange.KeyDown += this.ExchangeKeyDown;
this.partExchange.TextChanged += this.ExchangeTextChanged;
this.partSubscriber.KeyDown += this.SubscriberKeyDown;
// Template might be applied after dependency property set
// lets refresh UI in this case
this.UIFromValue();
}
So, I wonder if I should unsubscribe from those events and if so – where and how?
Well you’ve accepted an answer already and you may be able to get away that approach but its a too risky for my tastes. It assumes that
OnApplyTemplateonly ever gets called once. Potentially though your custom control may live a long time withOnApplyTemplategetting called more than once.I’ll outline here what hard-core control developers do, I’ll just use one
TextBoxfor brevity.Yes I know that this looks like overkill but the code is boilerplate and we use regions to rollup the repeative stuff so we can inspect code that actually does something interesting without being concerned with the plumbing. With this one instance its easy to roll it out to multiple parts.