Hello, MediaElement doesn't expose an event when its Position changes. You'll have to use a DispatcherTimer to query its Position from time to time. To begin, you can handle the MediaElement's MediaOpened event to get the video's length. Suppose your MediaElement is named MainMediaElement, and your Slider is named SliderProgress:
private void MainMediaElement_MediaOpened(object sender, RoutedEventArgs e)
{
SliderProgress.Maximum = MainMediaElement.NaturalDuration.TimeSpan.TotalSeconds;
SliderProgress.Value = 0;
}
Then you can create a DispatcherTimer.
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(100);
timer.Tick += new EventHandler(Timer_Tick);
Then handle the MediaElement's CurrentStateChanged event to start/stop the timer.
private void MainMediaElement_CurrentStateChanged(object sender, RoutedEventArgs e)
{
if (MainMediaElement.CurrentState == MediaElementState.Playing)
{
timer.Start();
}
else
{
timer.Stop();
}
}
In the timer's Tick event, set the Slider's Value.
private void Timer_Tick(object sender, EventArgs e)
{
SliderProgress.Value = MainMediaElement.Position.TotalSeconds;
}
Now the Slider's Value will change according to the MediaElement's Position. To control the MediaElement's Position with the Slider?, you must handle its MouseLeftButtonDown event to stop the timer, and handle MouseLeftButtonUp event to restart the timer.
private bool changedByUser;
private void SliderProgress_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
changedByUser = true;
timer.Stop();
}
private void SliderProgress_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (changedByUser && MainMediaElement.CurrentState == MediaElementState.Playing)
{
MainMediaElement.Position = TimeSpan.FromSeconds(SliderProgress.Value);
timer.Start();
changedByUser = false;
}
}
Hope it helps.
shanaolanxing - Please mark the posts as answers if they help and unmark if they don't.