Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

uwp - Which event happens when I touch the thumb of the slider?

I'm customize a slider to making seeking bar for video. What I want is that when I touch the thumb the video stops. Then I can drag the thumb and display the video corresponding to the slider's value. This is my Slider in XAML

<Slider Style="{StaticResource SliderStyle1}" Grid.Column="1" x:Name="volumeSlider" 
Width="Auto"  VerticalAlignment="Center" ValueChanged="volumeSlider_ValueChanged" 
DragLeave="volumeSlider_DragLeave" DragEnter="volumeSlider_DragEnter" 
DragStarting="volumeSlider_DragStarting" 
ManipulationStarted="volumeSlider_ManipulationStarted" ManipulationMode="All" 
Tapped="volumeSlider_Tapped"/>

enter image description here

I've try many event but none of them occur when mouse pointer starts touching the thumb (Not tap or click). Does anyone know about such event?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You would normally use PointerPressed event (see docs). However, this has two issues. First, the Thumb already handles such pointer interaction, so PointerPressed never bubbles out of the Slider. Secondly, it would be triggered for any location of the Slider, not only the thumb.

To work around this, you will need to handle the event on the Thumb itself. First, we will create a helper method that searches the visual tree:

public T FindChild<T>(DependencyObject parent)
{
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
    {
        var child = VisualTreeHelper.GetChild(parent, i);
        if (child is T typedChild)
        {
            return typedChild;
        }
        var inner = FindChild<T>(child);
        if (inner != null)
        {
            return inner;
        }
    }
    return default;
}

Note that this and many similar useful methods are available in the Windows Community Toolkit as part of Visual Tree Extensions.

Now, we search for the Thumb within the control:

var thumb = FindChild<Thumb>(MySlider);

Finally, we attach the PointerPressed event. Because it is already handled by the Slider control itself, we need to use AddHandler, that allows us to observe event that are marked as handled too:

thumb.AddHandler(
    UIElement.PointerPressedEvent, 
    new PointerEventHandler(Thumb_PointerPressed), 
    true);

And in the handler you can then do anything you require:

private void Thumb_PointerPressed(object sender, PointerRoutedEventArgs e)
{
    // ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...