Why Template of control is null at startup?

324 views Asked by At

I am trying to get Thumb of Slider.

_thumb = ((Track)AssociatedObject.Template.FindName("PART_Track", AssociatedObject))?.Thumb;

This throws NRE because Template is null. Why Template is null during application startup? and how can I fix that?

I tried code below

AssociatedObject.ApplyTemplate(); // no effect. returns false.
var template = AssociatedObject.Template; // returns null.

Even though I apply template its still null.

Previously I was overriding the slider OnApplyTemplate and Template was not null.

public override void OnApplyTemplate()
{
    // works fine.
    _thumb = ((Track)this.Template.FindName("PART_Track", this))?.Thumb;
    base.OnApplyTemplate();
}

But now I am trying to create Behavior for Slider rather than creating a subclass so I cant override. Any Idea how to fix this?

1

There are 1 answers

0
M.kazem Akhgary On BEST ANSWER

Oh, I could use Loaded event and get Thumb there.

AssociatedObject.Loaded += AssociatedObjectOnLoaded;

private void AssociatedObjectOnLoaded(object sender, RoutedEventArgs routedEventArgs)
{
    _thumb = ((Track)AssociatedObject.Template.FindName("PART_Track", AssociatedObject))?.Thumb;
}