views:

24

answers:

1

When inheriting a control in Silverlight, how do I find out if its template has already been applied?

I.e., can I reliably get rid of my cumbersome _hasTemplateBeenApplied field?

public class AwesomeControl : Control
{
    private bool _hasTemplateBeenApplied = false;

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        this._hasTemplateBeenApplied = true;
        // Stuff
    }

    private bool DoStuff()
    {
        if (this._hasTemplateBeenApplied)
        {
            // Do Stuff
        }
    }

}

+2  A: 

Nope that is the standard way to track whether the template has been applied.

AnthonyWJones
+1. I would add that, if you store private fields with template parts, though you could check them for being non-null, I would not recommend that: in theory all template parts are optional in a control.
Jeff Wilcox
@AnthonyWJones - all right then, I thought that they must keep track of that internally too somehow, but I guess they are just once again secretive with their internals :->
herzmeister der welten
@Jeff Wilcox, yes I also check for my `btnInnerAwesomeness != null` sometimes instead, but it's true that it feels kinda dirty.
herzmeister der welten
@herzmeister: Being "secretive with their internals" you might say "encapsulating private data in their objects". BTW, strictly speaking OnApplyTemplate can happen multiple times, although we are often only interested in that it has happened at least once.
AnthonyWJones
@herzmeister: Its more than "kinda dirty". Custom controls should not assume that the a specific template part will always be present in the actual template used for a specific instance. Consuming code can specify an entirely different template that may not contain all the elements that the control code expects to be present.
AnthonyWJones
yes I am aware that template parts are optional, as Jeff also pointed out. However, my `btnInnerAwesomeness` might be the essence of my Control. My Control's purpose and life might be pointless without it. In such a case it may justified to check for it I think.
herzmeister der welten
@herzmeister: Good point.
AnthonyWJones