SaveState / LoadState后无法设置MediaElement Source
( 注意:所有代码都已严格简化。 )
问题
暂停/恢复后未设置MediaElement源。 设置源后,CurrentState会快速更改为“已关闭”。
我正在处理MediaFailed事件 – 它不会触发。 我也在处理MediaOpened事件,它也不会触发。
细节
我有以下方法更新MediaElement的Source。 只要应用程序在被暂停后没有尝试恢复,它就能很好地工作。
private async void UpdateMediaElementSource(object sender, EventArgs e) { var videoSource = this.DefaultViewModel.CurrentSource; // a string var file = await StorageFile.GetFileFromPathAsync(videoSource); var videoStream = await file.OpenAsync(FileAccessMode.Read); this.videoMediaElement.SetSource(videoStream, file.ContentType); // The above line works many times as long as the app is not trying to Resume. }
当应用程序处于Suspended状态时,它会调用SaveState方法:
protected async override void SaveState(Dictionary pageState) { pageState["MediaElementSource"] = this.DefaultViewModel.CurrentSource; // I also made the videoStream global so I can dispose it — but no dice. this.videoStream.Dispose(); this.videoStream = null; }
当应用程序恢复时,它会调用LoadState方法:
protected async override void LoadState(Object navigationParameter, Dictionary pageState) { string source = string.Empty; if (pageState != null) { if (pageState.ContainsKey("MediaElementSource")) { source = (string)pageState["MediaElementSource"]; } } var document = PublicationService.GetDocument(this.currentDocumentIdNumber); this.DefaultViewModel = new DocumentViewModel(document); this.DefaultViewModel.CurrentMarkerSourceChanged += UpdateMediaElementSource; if (!string.IsNullOrEmpty(source)) { // This causes the UpdateMediaElementSource() method to run. this.DefaultViewModel.CurrentSource = source; } }
我对此问题表示感谢。 如果您需要更多详细信息,请与我们联系。
因此,事实certificatemediaElement的Source在被添加到可视树之前被设置了。
通常,这样做不是问题:
mediaElement.Source = whatever;
但这样做是一个问题:
mediaElement.SetSource(stream, MimeType);
结论
调用SetSource(…)时,请确保您的MediaElement是VisualTree的一部分。
让我的上述代码工作的一种简单方法是添加一个全局bool,一旦mediaElement.Loaded
事件被触发,该bool设置为true 。 然后,在调用SetSource()
的代码中,将其包装在if(_mediaElementLoaded)
块中。