Setting a Silverlight slider control at initialization

Setting a Silverlight slider control at initialization

I recently ran into a problem where I needed a Silverlight slider control pre-populated with a specific value when the page loaded, but if you use the slider`s ValueChanged event in the code behind file, it dies. Why? Because as the page loads and initializes, the code behind is trying to run and the slider control hasn`t finished being created yet. Putting the values I wanted them to start at worked fine, as long as you put them after the Initialize(); call in Page_Load, but I still wanted the ValueChanged method to fire when the value changed on the slider. Here`s what I did to make sure the ValueChanged method fires and I can still pre-populate the slider at initialization:

Slider slider = (Slider)this.FindName(“slidername”);
if (slider == null)
return;
else
{
// Do something
}

The first line there looks to make sure the control was created before even continuing. If it exists, it then will allow whatever you want from it without throwing an error.

Comments are closed.