Win10控件: MediaElement

来源:互联网 发布:布料运算软件 编辑:程序博客网 时间:2024/06/01 08:42

当在某页面中使用MediaElement时,默认情况下如果导航到另一页面,音乐将停止,下面给出解决方案。


1、在App.xaml.cs文件中定位到OnLaunched函数,将如下代码替换原来的

protected override void OnLaunched(LaunchActivatedEventArgs e)        {#if DEBUG            if (System.Diagnostics.Debugger.IsAttached)            {                this.DebugSettings.EnableFrameRateCounter = true;            }#endif            var rootFrame = new Frame();            rootFrame.Style = Resources["RootFrameStyle"] as Style;            rootFrame.Navigate(typeof(MainPage));            Window.Current.Content = rootFrame;            Window.Current.Activate();         }

2、新建或使用原工程中的资源字典,添加如下样式:

      

<Style  x:Key="RootFrameStyle" TargetType="Frame">        <Setter Property="Template">            <Setter.Value>                <ControlTemplate TargetType="Frame">                    <Grid>                        <MediaElement AudioCategory="BackgroundCapableMedia" AutoPlay="True"/>                        <ContentPresenter />                    </Grid>                </ControlTemplate>            </Setter.Value>        </Setter></Style>


3、别忘了在App.xaml文件中使用这个样式文件:

    

  <Application.Resources>        <ResourceDictionary>            <ResourceDictionary.MergedDictionaries>                <ResourceDictionary Source="StylesDictionary.xaml" />            </ResourceDictionary.MergedDictionaries>        </ResourceDictionary>    </Application.Resources>

4、在需要MediaElement页面(如MainPage)的代码文件中新建load事件:

     

private void OnLoaded(object sender, RoutedEventArgs e)        {            DependencyObject rootGrid = VisualTreeHelper.GetChild(Window.Current.Content, 0);            musicPlayer = (MediaElement)VisualTreeHelper.GetChild(rootGrid, 0);        }

     musicPlayer是页面中定义的MediaElement类

     别忘了在构造函数中加上这一句:this.Loaded += OnLoaded;


至此就可以在不同页面中使用这个MediaElement了。给musicPlayer添加Source属性就可以全局播放音频,即使导航到其他页面也不会有影响。

0 0
原创粉丝点击