获取滑块的拇指

时间:2010-07-12 23:13:41

标签: wpf wpf-controls

我只想弄清楚如何在WPF中获得滑块的拇指,如下所示:

Slider mySlider = new Slider();

Thumb thumb = slider.Thumb;

现在我知道这不可能这么简单;但必须有一个解决这个问题的工作。如果您知道,请告诉我。

谢谢!

3 个答案:

答案 0 :(得分:10)

Slider有一个TemplatePartAttribute,声明它应该有一个名为PART_Track的{​​{3}}类型的模板部分。 Track可以为我们提供Thumb的参考。请注意,可以为Slider模板提供Track,在这种情况下,不会有Thumb

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

答案 1 :(得分:2)

VisualTreeHelper的帮助下,我自己找到了解决方案。任何优化都非常感激:

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 :(得分:1)

如果您只是想向事件添加事件处理程序,并且不想等待或强行渲染以避免null成为slider.AddHandler(Thumb.DragStartedEvent, new DragStartedEventHandler((sender, e) => { // Handling code })); ,则可以执行以下操作:

Sub roll()

Dim sh As Worksheet
Dim c As Range


For Each sh In ActiveWorkbook.Sheets

With sh

Application.ScreenUpdating = False

Columns("B:AB").Select
Selection.EntireColumn.Hidden = False


        For Each c In Range("b8:ab8").Cells
            If c.Value = "X" Then
            c.EntireColumn.Hidden = True
            End If

        Next c
            End With

Next sh

Application.ScreenUpdating = True

End Sub