7

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!

Charles Stewart
  • 11,661
  • 4
  • 46
  • 85
Carlo
  • 25,602
  • 32
  • 128
  • 176

3 Answers3

12

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;
}
Quartermeister
  • 57,579
  • 7
  • 124
  • 111
3

If you just want to add an event handler to the thumb and don't want to wait or force rendering to avoid slider.Template being null, you can do something like this:

slider.AddHandler(Thumb.DragStartedEvent, new DragStartedEventHandler((sender, e) =>
{
    // Handling code
}));
tuanh118
  • 311
  • 2
  • 5
  • This works well in OnApplyTemplate of a custom control CONTAINING the slider. Everything else I've tried with mouse events applies to the entire custom control -- not just the slider. :) – Alan Wayne Jan 18 '19 at 23:51
2

Found the solution on my own, with a little help from the VisualTreeHelper. Any optimization greatly appreciated:

private Thumb Thumb
{
    get
    {
        return GetThumb(this /* the slider */ ) as Thumb;;
    }
}

private DependencyObject GetThumb(DependencyObject root)
{
    if (root is Thumb)
        return root;

    DependencyObject thumb = null;

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++)
    {
        thumb = GetThumb(VisualTreeHelper.GetChild(root, i));

        if (thumb is Thumb)
            return thumb;
    }

    return thumb;
}
Carlo
  • 25,602
  • 32
  • 128
  • 176