Get the Thumb of a Slider

2019-03-30 22:42发布

问题:

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!

回答1:

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


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


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