Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 598
Carlo Avatar asked Jul 12 '10 23:07

Carlo


3 Answers

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;
}
like image 194
Quartermeister Avatar answered Oct 15 '22 20:10

Quartermeister


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
}));
like image 3
tuanh118 Avatar answered Oct 15 '22 21:10

tuanh118


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;
}
like image 2
Carlo Avatar answered Oct 15 '22 22:10

Carlo