Hugoagogo
Hugoagogo

Reputation: 1646

Prevent original template being applied in inherited control

I am having an issue in an application where I would like to derive my own custom control from a control included in a commercial library (scichart).

I am overriding OnApplyTemplate, as in the below code, but am running into an issue where when calling GetAndAssertTemplateChild (A function in the library that is pretty much the same as GetTemplateChild but throws and error if the result is equal to null) the part cannot be found in the template.

While investigating this issue I found that OnApplyTemplate is being called multiple times, it is first called with the template of the control being inherited from, and is then recalled with the template of the new control. Is there any way to avoid this and to never apply the base classes template.

public override void OnApplyTemplate()
{
    base.OnApplyTemplate();

    AnnotationRoot = GetAndAssertTemplateChild<Grid>("PART_LineAnnotationRoot");
    _line = GetAndAssertTemplateChild<Line>("PART_Line");
    _ghostLine = GetAndAssertTemplateChild<Line>("PART_GhostLine");
    _label = GetAndAssertTemplateChild<TextBlock>("PART_Label");
}

Upvotes: 0

Views: 98

Answers (1)

mm8
mm8

Reputation: 169200

Is there any way to avoid this and to never apply the base classes template

If you only want to call the derived class' OnApplyTemplate() method, you should avoid calling the base class' method in the overridden method:

public override void OnApplyTemplate()
{
    //DON't CALL THIS ONE: base.OnApplyTemplate();

    AnnotationRoot = GetAndAssertTemplateChild<Grid>("PART_LineAnnotationRoot");
    _line = GetAndAssertTemplateChild<Line>("PART_Line");
    _ghostLine = GetAndAssertTemplateChild<Line>("PART_GhostLine");
    _label = GetAndAssertTemplateChild<TextBlock>("PART_Label");
}

And if you want to provide your own default custom ControlTemplate from scratch, you should define a static constructor in your control class:

static YourControl()
{
    DefaultStyleKeyProperty.OverrideMetadata(typeof(YourControl),
        new FrameworkPropertyMetadata(typeof(YourControl)));
}

...and define the default template in a ResourceDictionary called "generic.xaml" located in a folder called "Themes" at the root folder of the project in which the control class is defined.

Upvotes: 1

Related Questions