将 MediaElement 绑定到 WPF 中的滑块位置 [英] Binding MediaElement to slider position in WPF

查看:29
本文介绍了将 MediaElement 绑定到 WPF 中的滑块位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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}" />

推荐答案

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

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):

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

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;
                }
            }
        }

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

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

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

事件处理程序是:

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

这篇关于将 MediaElement 绑定到 WPF 中的滑块位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆