将 MediaElement 绑定到 WPF 中的滑块位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10208959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 23:23:30  来源:igfitidea点击:

Binding MediaElement to slider position in WPF

wpfslidermediaelement

提问by HomeMade

Tried binding Maximum value of slider to media element's duration and binding slider's current value to the position of media element, but but for some reasons it doesn't.

尝试将滑块的最大值绑定到媒体元素的持续时间并将滑块的当前值绑定到媒体元素的位置,但由于某些原因它没有。

I want the slider to move it's thumb while the video is playing.

我希望滑块在播放视频时移动它的拇指。

<Slider x:Name="videoSlider" Value="{Binding ElementName=mp3MediaElement, Path=Position}" 
ValueChanged="videoSlider_ValueChanged" IsMoveToPointEnabled="True" 
Maximum="{Binding ElementName=mp3MediaElement, Path=NaturalDuration}" 
AllowDrop="True" DataContext="{Binding ElementName=mp3MediaElement}" />

回答by Dor Cohen

I didn't use binding.. I had a similar issue and used timer for this (My code is in Silverlight by it suppose to be the same on WPF):

我没有使用绑定..我有一个类似的问题并为此使用了计时器(我的代码在 Silverlight 中,它假设在 WPF 上是相同的):

First direction (movie updates the slider)

第一方向(电影更新滑块)

private TimeSpan TotalTime;

private void MyMediaElement_MediaOpened(object sender, RoutedEventArgs e)
        {
            TotalTime = MyMediaElement.NaturalDuration.TimeSpan;

            // Create a timer that will update the counters and the time slider
            timerVideoTime = new DispatcherTimer();
            timerVideoTime.Interval = TimeSpan.FromSeconds(1);
            timerVideoTime.Tick += new EventHandler(timer_Tick);
            timerVideoTime.Start();
        }

void timer_Tick(object sender, EventArgs e)
        {
            // Check if the movie finished calculate it's total time
            if (MyMediaElement.NaturalDuration.TimeSpan.TotalSeconds > 0)
            {
                if (TotalTime.TotalSeconds > 0)
                {
                    // Updating time slider
                    timeSlider.Value = MyMediaElement.Position.TotalSeconds /
                                       TotalTime.TotalSeconds;
                }
            }
        }

Second direction (user updates the slider)
on form ctor or something like this write the following line:


在form ctor上的第二个方向(用户更新滑块)或类似的东西写下一行:

timeSlider.AddHandler(MouseLeftButtonUpEvent, 
                      new MouseButtonEventHandler(timeSlider_MouseLeftButtonUp), 
                      true);

and the event handler is:

事件处理程序是:

private void timeSlider_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (TotalTime.TotalSeconds > 0)
            {
                MyMediaElement.Position = TimeSpan.FromSeconds(timeSlider.Value * TotalTime.TotalSeconds);
            }
        }

回答by Yuriy Zanichkovskyy

Both Slider properties Value and Maximum are of type Double. You are trying to bind to values of types TimeSpanand Durationcorrespondingly and thats why the binding system doesn't work in your case.

Slider 属性 Value 和 Maximum 都是 Double 类型。您正在尝试绑定到类型TimeSpanDuration相应的值,这就是绑定系统在您的情况下不起作用的原因。

You may try to write a convertor, or to bind to NaturalDuration.TimeSpan.TotalSecondsproperty.

您可以尝试编写转换器或绑定到NaturalDuration.TimeSpan.TotalSeconds属性。

Hope this helps.

希望这可以帮助。

By the way if some of your bindings do not work you may check binding errors in Visual Studio "Output" window.

顺便说一句,如果您的某些绑定不起作用,您可以在 Visual Studio“输出”窗口中检查绑定错误。

回答by G.Y

I had the same problem, the slider was not updating UI of the MediaElement..
I spent quite some time trying to fix it and I am not sure it will help others.
But Just in case someone else hit that problem, do note that there is a ScrubbingEnabledproperty in media element which allows the UI of the MediaElement to automatically seek the correct picture according to the position.
Very useful when you are in a pause-mode and trying to drag the slider.
Just add: ScrubbingEnabled="True"in the XAML of your MediaElement.

我遇到了同样的问题,滑块没有更新 MediaElement 的 UI。
我花了很多时间试图修复它,但我不确定它会帮助其他人。
但是为了防止其他人遇到这个问题,请注意媒体元素中有一个ScrubbingEnabled属性,它允许 MediaElement 的 UI 根据位置自动寻找正确的图片。
当您处于暂停模式并尝试拖动滑块时非常有用。
只需添加:ScrubbingEnabled="True"在您的 MediaElement 的 XAML 中。

回答by koopa

Here's what I ended up using for my UWP app.

这是我最终用于我的 UWP 应用程序的内容。

This answer just addresses the specific question; moving the slider thumb in response to playback. It doesn't handle changing the video position in response to the user moving the slider.

这个答案只是针对具体问题;响应播放移动滑块拇指。它不处理响应用户移动滑块来更改视频位置。

First add these:

首先添加这些:

private DispatcherTimer timerVideoPlayback;

private void TimerVideoPlayback_Tick(object sender, object e)
{
    long currentMediaTicks = mediaElement.Position.Ticks;
    long totalMediaTicks = mediaElement.NaturalDuration.TimeSpan.Ticks;

    if (totalMediaTicks > 0)
        slider.Value = (double)currentMediaTicks / totalMediaTicks * 100;
    else
        slider.Value = 0;
}

Then when your video starts, start the timer:

然后当您的视频开始时,启动计时器:

timerVideoPlayback = new DispatcherTimer();
timerVideoPlayback.Interval = TimeSpan.FromMilliseconds(10);
timerVideoPlayback.Tick += TimerVideoPlayback_Tick;
timerVideoPlayback.Start();

I used a 10 ms interval to keep the slider motion steady. Use any value you like.

我使用了 10 毫秒的间隔来保持滑块运动稳定。使用您喜欢的任何值。

And don't forget to stop that timer when playback ends:

并且不要忘记在播放结束时停止该计时器:

timerVideoPlayback.Stop();