Mouse click on WPF (Time)Slider has no effect when slider thumb is moving bound to a timer

Viewed 532

I use MediaElement and (Time)Slider to play and control playing of a video. I used answer 2 to this question as a base.

In addition to the dragging capability I would also like the slider thumb to be moved to a mouse click point. This works ok when the MediaElement and (Time)Slider are paused, but when the video is playing a mouse click has no effect

Here is my code

XAML:

<MediaElement Source="..." 
              Name="mediaView"
              Height="450" LoadedBehavior="Manual" UnloadedBehavior="Stop" Stretch="UniformToFill" 
              MediaOpened="OnMediaOpened" MediaEnded="OnMediaEnded" MediaFailed="OnMediaFailed" Grid.Row="0" Grid.Column="0"/>
<Grid Name="mediaBar" VerticalAlignment="Bottom" Margin="5,10,5,0" Background="#B2282828"  Grid.Row="0" Grid.Column="0">
    <!-- ... -->
    <Slider Name="timeSlider" Margin="5,5,5,0" 
            Thumb.DragStarted="OnDragStarted" Thumb.DragCompleted="OnDragCompleted" ValueChanged="OnTimeSliderValueChanged" 
            PreviewMouseLeftButtonUp="OnMouseLeftButtonUp" IsMoveToPointEnabled="True"
            MinWidth="200" FlowDirection="LeftToRight"  
            Grid.Column="4" Cursor="ScrollWE" VerticalAlignment="Center"/>
    <!-- ... -->
</Grid>

relevant c# part:

private void OnDragStarted(object sender, DragStartedEventArgs args)
{
    isDragging = true;
    ticks.Stop();
}
private void OnDragCompleted(object sender, DragCompletedEventArgs args)
{
    isDragging = false;
    int SliderValue = (int)timeSlider.Value;

    TimeSpan ts = new TimeSpan(0, 0, 0, 0, SliderValue);
    mediaView.Position = ts;
    if(currentStatus == Status.PLAYING)
        ticks.Start();
}
private void OnMouseLeftButtonUp(object sender, EventArgs ea)
{
    if(!isDragging)
    {
        mediaView.Pause();
        ticks.Stop();

        int SliderValue = (int)timeSlider.Value; // when video is playing this not the point of the mouse click

        // ...
    }
}

I can understand that timeSlider.Value delivers the current point in time instead of the mouse click position when the video is playing.

Is there another way to measure the position of the mouse click and update the slider value with that ?

Or a better solution for the Mouse-click-while-slider-is-running-situation ?

1 Answers

Try this:

private void OnMouseLeftButtonUp(object sender, MouseButtonEventArgs ea)
        {
            mediaView.Position = TimeSpan.FromSeconds((int)(mediaView.NaturalDuration.TimeSpan.TotalSeconds * (double)(ea.GetPosition(timeSlider).X / this.Width)));
        }
Related