【问题标题】:Get Thumb of a Slider in UWP在 UWP 中获取滑块的拇指
【发布时间】:2022-01-12 12:06:44
【问题描述】:

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

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

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

我在 WPF 中看到了多种方法,但在 UWP 中没有。

【问题讨论】:

    标签: c# uwp uwp-xaml


    【解决方案1】:

    要从滑块访问 Thumb,请尝试以下操作:

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

    2:使用该函数从父级获取子级

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

    【讨论】:

    • 谢谢!它终于奏效了,我不知道使用 VisualTreeHelper 有多么容易,我是 C# 新手,有些东西一开始似乎很难理解。再次,非常感谢您
    • 不客气:D
    猜你喜欢
    • 2020-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多