wpfwpf-controls

Get the Thumb of a Slider


I'm just trying to figure out a way to get the Thumb of a Slider in WPF, something like so:

Slider mySlider = new Slider();
Thumb thumb = slider.Thumb;

Now I know it's not possible as simple as this; but there must be a work around this. Let me know if you know any.

Thanks!


Solution

  • Slider has a TemplatePartAttribute that declares it should have a template part called PART_Track of type Track. The Track can give us a reference to the Thumb. Keep in mind that it's possible to give the Slider a template with no Track, in which case there will be no Thumb.

    private static Thumb GetThumb(Slider slider)
    {
        var track = slider.Template.FindName("PART_Track", slider) as Track;
        return track == null ? null : track.Thumb;
    }