views:

26

answers:

2

Hi, 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 konw it's not possible as simple as this; but there must be a work around this. Let me know if you know any.

Thanks!

EDIT:

Btw, I blogged my problem and solution:

http://wpfdude.blogspot.com/2010/07/rule-of-thumb-sliders-thumb.html

A: 

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
A: 

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