Carlo
Carlo

Reputation: 25969

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!

Upvotes: 9

Views: 6441

Answers (3)

tuanh118
tuanh118

Reputation: 361

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
}));

Upvotes: 3

Quartermeister
Quartermeister

Reputation: 59179

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;
}

Upvotes: 14

Carlo
Carlo

Reputation: 25969

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;
}

Upvotes: 2

Related Questions