当滑鼠拇指移动绑定到计时器时,在WPF(时间)上单击鼠标不会起作用。

时间:2018-11-08 13:19:36

标签: wpf slider

我使用MediaElement和(Time)Slider播放和控制视频的播放。 我以answer 2 to this question为基础。

除了具有拖动功能外,我还希望将滑块移至鼠标单击点。 当MediaElement和(Time)Slider暂停时,此方法可以正常运行,但是在播放视频时,单击鼠标没有效果

这是我的代码

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>

相关的c#部分

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

        // ...
    }
}

我可以理解,timeSlider.Value会在播放视频时提供当前时间点,而不是鼠标单击位置。

还有另一种方法来测量鼠标单击的位置并以此来更新滑块值吗?

对于滑行鼠标正在运行的情况还是更好的解决方案?

1 个答案:

答案 0 :(得分:1)

尝试一下:

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