[英]Access MediaElement Control of Different Page from App.xaml.cs
I have a MediaElement
control in Media.xaml
which I would like to access from App.xaml.cs
like this: 我在
Media.xaml
有一个MediaElement
控件,我想从App.xaml.cs
访问它,如下所示:
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//Media.MediaElement.Pause();
deferral.Complete();
}
Can anyone tell me how to do that? 谁能告诉我该怎么做?
First, I added x:FieldModifier="Public"
to the MediaElement
: 首先,我向
MediaElement
添加了x:FieldModifier="Public"
:
<MediaElement Name="meMedia" x:FieldModifier="Public"/>
Then, added this code to App.xaml.cs
: 然后,将此代码添加到
App.xaml.cs
:
if (rootFrame.Content.GetType.Name == "Media") {rootFrame.Content.mc.Pause();}
You could create a public property: 您可以创建一个公共财产:
Media.xaml: Media.xaml:
<MediaElement x:Name="mediaElement" ... />
Media.xaml.cs: Media.xaml.cs:
public MediaElement
{
get { return mediaElement; }
}
I don't know the details of your program structure, but there should be a way of getting the currently active Media instance. 我不知道您的程序结构的详细信息,但是应该有一种获取当前活动的Media实例的方法。 If you really don't have such a reference (and if there is also only one Media instance), a workaround might be to create a static instance accessor property:
如果您确实没有这样的引用(并且也只有一个Media实例),则解决方法是创建一个静态实例访问器属性:
Media.xaml.cs: Media.xaml.cs:
public static Media Instance { get; private set; }
// constructor
public Media()
{
...
Instance = this;
}
Now you may write this in App.xaml.cs: 现在,您可以在App.xaml.cs中编写以下代码:
Media.Instance.MediaElement.Pause();
You can use the following code to access the current Media page and pause its MediaElement: 您可以使用以下代码访问当前的“媒体”页面并暂停其MediaElement:
var frame = (Frame)Window.Current.Content;
var page = frame.Content as Media;
if (page != null && page.MediaElement.CanPause) page.MediaElement.Pause();
However, if your intent is to pause the playing media when the user switches to another app, you should use the Window.Current.CoreWindow.VisibilityChanged event. 但是,如果您打算在用户切换到另一个应用程序时暂停播放媒体,则应使用Window.Current.CoreWindow.VisibilityChanged事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.