Get the thumb of the slider

I'm just trying to figure out how to get the thumb of a slider in WPF, something like this:

Slider mySlider = new Slider();

Thumb thumb = slider.Thumb;

Now I know that this is impossible as simple as that; but there has to be work around this. Let me know if you know.

Thank!

+3
source share
2 answers

Sliderhas TemplatePartAttributewhich declares that it should have a part of the template called PART_Tracktype Track. Trackcan give us a link to Thumb. Keep in mind that you can give a template Sliderwithout Track, and in this case will not Thumb.

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

Found a solution on my own, with a little help from VisualTreeHelper. Any optimization is 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;
}
+2

Source: https://habr.com/ru/post/1754323/


All Articles