Windows phone 8 滑块绑定仅在单击后有效

Windows phone 8 slider binding works only after a click(Windows phone 8 滑块绑定仅在单击后有效)

本文介绍了Windows phone 8 滑块绑定仅在单击后有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Windows Phone 8 上编写一个音频应用程序.我创建了一个 MediaElement 和一个搜索栏(滑块):

I am writing an audio app on Windows Phone 8. I've created a MediaElement and a seek-bar(slider):

<MediaElement x:Name="player" CurrentStateChanged="GetTrackDuration" />
<Slider x:Name="playerSeekBar" Value="{Binding ElementName=player, Path=Position, 
 Mode=TwoWay, Converter={StaticResource PositionConverter}}" SmallChange="1" LargeChange="1"/>

这是我的转换器代码:

public class PositionConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        double position = 0;
        TimeSpan timespan = TimeSpan.Parse(value.ToString());
        position = timespan.TotalSeconds;

        return position;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
            return TimeSpan.FromSeconds((double)value);
    }
}

这里是 CurrentStateChanged 事件代码:

And here is the CurrentStateChanged event code:

private void GetTrackDuration(object sender, RoutedEventArgs e)
{
    var player = (MediaElement)sender;
    if (player.CurrentState == System.Windows.Media.MediaElementState.Playing)
        playerSeekBar.Maximum = player.NaturalDuration.TimeSpan.TotalSeconds;
}

似乎一切正常,但是与滑块的绑定存在一个问题 - 在我单击应用程序内部的某个位置之前它不会更新 - 我的意思是我可能会单击一个未与滑块连接的按钮或媒体元素或空白空间.单击滑块后,滑块正在更新,一切正常.顺便说一句,音乐正常播放 - 即使在滑块未更新的开头也是如此.我试图在互联网上查看,但我不知道该问什么,这就是我向您寻求帮助的原因.如果有人知道我可以在哪里搜索解决方案,我将不胜感激!:)

It all seems to work OK, however there is one problem with the binding to slider - it doesn't update until I click somewhere inside the app - I mean i may click on a button that isn't connected with slider or media element or on a empty space. After I click the slider is being updated and everything works nice. BTW, the music plays normally - even at the beginning when the slider is not being updated. I tried to look on the Internet, however I am not sure what to ask, that's why I am asking You for help. If someone just knows where I could search for the solution, I would be very grateful!:)

提前感谢您的帮助!

推荐答案

Slider 获得 Focus 时看起来像一个问题,我试图找到一个重定向 Focus 的解决方案,但到目前为止 - 我还没有找到它.相反,我对您的代码提出了不同的建议和几句话:

It looks like a problem when Slider gets Focus, I've tried to find a solution with redirecting Focus, but so far - I haven't found it. Instead I've a diffrent proposal and few remarks to your code:

  1. 在打开媒体而不是在 PlayState 更改时获取曲目持续时间:

  1. Get track duration when Media is Opened not when PlayState changes:

private void player_MediaOpened(object sender, RoutedEventArgs e)
{
    playerSeekBar.Maximum = (sender as MediaElement).NaturalDuration.TimeSpan.TotalSeconds;
}

  • 您的 Slider 可能会随着 MediaElement 位置的每一次微小变化而更新.我认为它不是必需的 - 例如可以每秒更新一次.所以我的建议是 - 将您的 Slider 绑定到一个属性,并每秒通知 PropertyChanged(使用 DispatcherTimer):

    // In this case we need INotifyPropertyChanged - 
    public partial class MainPage : PhoneApplicationPage, INotifyPropertyChanged
    {
    
    // implementing interface
    public event PropertyChangedEventHandler PropertyChanged;
    public void RaiseProperty(string property = null)
    {
        if (this.PropertyChanged != null)
            this.PropertyChanged(this, new PropertyChangedEventArgs(property));
    }
    
    // Property for Binding
    public double SlideValue
    {
        get { return player.Position.TotalSeconds; }
        set { player.Position = TimeSpan.FromSeconds(value); }
    }
    
    DispatcherTimer timer = new DispatcherTimer(); // timer
    
    // Get the duration when Media File is opened
    private void player_MediaOpened(object sender, RoutedEventArgs e)
    {
        playerSeekBar.Maximum = (sender as MediaElement).NaturalDuration.TimeSpan.TotalSeconds;
    }
    
    public MainPage()
    {
        InitializeComponent();
        this.DataContext = this;  // Set the DataContext
        Play.Click += Play_Click;  // My play method
        timer.Interval = TimeSpan.FromSeconds(1);
        timer.Tick += (s, e) => { RaiseProperty("SlideValue"); };
    }
    
    private void Play_Click(object sender, RoutedEventArgs e)
    {
        player.AutoPlay = true;
        player.Source = new Uri("music.mp3", UriKind.RelativeOrAbsolute);
        timer.Start();  // DON'T forget to start the timer.
    }
    

  • 在这种情况下,您不再需要转换器,您的 XAML 代码可能如下所示:

    In this case you no longer need Converters, and your XAML code can look like this:

    <MediaElement x:Name="player" MediaOpened="player_MediaOpened"/>
    <Slider x:Name="playerSeekBar" Value="{Binding SlideValue, Mode=TwoWay}" SmallChange="1" LargeChange="1"/>
    

    上面的代码可能还需要一些改进,但效果很好.

    Above code probably still needs some improvements, but works quite fine.

    EDIT - 没有 DataBinding 和 INotifyPropertyChanged 的​​方法

    EDIT - method without DataBinding and INotifyPropertyChanged

    您也可以在没有绑定的情况下以更简单的方式完成您的任务,只需使用 TimerLostMouseCapture:

    You can also accomplish your task simpler way without Binding, just using Timer and LostMouseCapture:

    public partial class MainPage : PhoneApplicationPage
    {
        private double totalSeconds = 1;
    
        DispatcherTimer timer = new DispatcherTimer();
    
        private void player_MediaOpened(object sender, RoutedEventArgs e)
        {
            totalSeconds = (sender as MediaElement).NaturalDuration.TimeSpan.TotalSeconds;
        }
    
        public MainPage()
        {
            InitializeComponent();
            Play.Click += Play_Click;
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += (s, e) => { playerSeekBar.Value += (double)(1 / totalSeconds); };
            playerSeekBar.LostMouseCapture += (s, e) =>
            { player.Position = TimeSpan.FromSeconds(playerSeekBar.Value * totalSeconds); };
        }
    
        private void Play_Click(object sender, RoutedEventArgs e)
        {
            player.AutoPlay = true;
            player.Source = new Uri("music.mp3", UriKind.RelativeOrAbsolute);
            timer.Start();  // DON'T forget to start the timer.
        }
    }
    

    在 XAML 中:

    <MediaElement x:Name="player" MediaOpened="player_MediaOpened"/>
    <Slider x:Name="playerSeekBar" Value="0" SmallChange="0.01" Maximum="1.0"/>
    

    希望这会有所帮助.

    这篇关于Windows phone 8 滑块绑定仅在单击后有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

    本文标题为:Windows phone 8 滑块绑定仅在单击后有效

    基础教程推荐