views:

239

answers:

2

Hello,
I have a custom control template that contains a Slider control.
I name that as a part in the class that implements the custom control:

[TemplatePart(Name = MapZoomSliderName, Type = typeof(Slider))]

In the OnApplyTemplate() override, I get the Slider:

        MapZoomSlider = (Slider) GetTemplateChild("MapZoomSlider");
        if (null != MapZoomSlider)
        {

            MapZoomSlider.ValueChanged +=new RoutedPropertyChangedEventHandler<double>(MapZoomSlider_ValueChanged);
            MapZoomSlider.Value = InitSliderValue;  // crash
            _lastSliderValue = MapZoomSlider.Value;
        }

When I try to set the Slider's Value property, the app crashes with "Object reference not set to an instance of an object."
Getting the slider's value works as expected.
What do I need to do to set the Slider's value at run time?
Thanks for any tips...

A: 

What is "InitSliderValue"? Maybe its the wrong value type? (Must be a double) Also, zero or negative may not be a valid value.

Shawn Wildermuth
A: 

It appears the problem was in setting the ValueChanged handler before changing the Value property. The ValueChanged handler tries to manipulate other parts of app, parts that might not be ready yet.
If I set the value, then add the handler, it works as desired.

MapZoomSlider.Value = InitSliderValue;  // all good
MapZoomSlider.ValueChanged +=new RoutedPropertyChangedEventHandler<double>(MapZoomSlider_ValueChanged);
Number8

related questions