在 UWP 中获取滑块的缩略图

Get Thumb of a Slider in UWP

我为滑块制作了自定义样式,我只更改了 Thumb 的形状。 我想做的是有一个功能,可以在触发时更改 Thumb 的大小(可能通过按钮)。 我创建自定义样式的方法是:右键单击 Slider -> Edit Template -> Edit a copy

我的问题是我不知道如何访问滑块的拇指... 我想要这样的东西

Thumb myThumb = mySlider.GetTemplateChild("horizontalThumb");
myThumb.Height = 50;

我在 WPF 中看到了多种执行此操作的方法,但在 UWP 中却没有。

要从 Slider 访问 Thumb,试试这个:

1:将 XAML 中的 Loaded 事件添加到您的滑块

2:使用这个函数从parent中获取child

//Get the acutal element from the parent object using the VisualTreeHelper:
//Parameters:
//parent = The object to get the element from
//childname = The name of the childobject to find
private DependencyObject GetElementFromParent(DependencyObject parent, string childname)
{
    int count = VisualTreeHelper.GetChildrenCount(parent);
    for (int i =0; i < count; i++)
    {
        var child = VisualTreeHelper.GetChild(parent, i);
        if (child is FrameworkElement childframeworkelement && childframeworkelement.Name == childname)
            return child;

        var FindRes = GetElementFromParent(child, childname);
        if (FindRes != null)
            return FindRes;
    }
    return null;
}
    

3:将此代码放入您的 slider_loaded 事件中以从 Thumb 获取数据:

private void Slider_Loaded(object sender, RoutedEventArgs e)
{
    var SliderThumb = GetElementFromParent(sender as DependencyObject, "HorizontalThumb"); //Make sure to put the right name for your slider layout options are: ("VerticalThumb", "HorizontalThumb")
    if (SliderThumb != null)
    {
        if(SliderThumb is Thumb thumb)
        {
            //Here you can change everything you like:
            thumb.Background = new SolidColorBrush(Colors.Blue);
            thumb.CornerRadius = new CornerRadius(5);
            thumb.Width = 10;
            thumb.Height = 10;
        }
        else
        {
            //SliderThumb is not an object of type Thumb
        }
    }
    else
    {
        //SliderThumb is null
    }
}