MediaElement.Position没有反映UWP的变化

时间:2017-09-20 11:28:01

标签: c# uwp windows-runtime

我有一个MediaElement,其设置位置没有反映。

if(Playback.CanSeek)
   Playback.Position = new TimeSpan(0,0,4);

请注意MediaElement当前已暂停且自动播放已开启等。 没有错误,但该行不会更改Position属性。

还在Core Dispatcher中运行了代码,但仍然没有运气。

编辑:另请注意,此MediaElement是从C#创建的,与XAML无关,因为它在ViewModel中作为库。

谢谢。

1 个答案:

答案 0 :(得分:1)

要解决此问题,您必须将MediaElement对象添加到XAML UI中。

例如,如下代码:

<Grid x:Name="root" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Button Content="set" Click="Button_Click"></Button>
</Grid>
MediaElement playback = new MediaElement();
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);

    var file = await Package.Current.InstalledLocation.GetFileAsync("test.mp3");
    if (file != null)
    {
        var stream = await file.OpenReadAsync();
        playback.SetSource(stream, file.ContentType);
    }
    playback.Play();
    root.Children.Add(playback);
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    if (playback.CanSeek)
    {
        playback.Position = TimeSpan.FromSeconds(5);
    }
}