【发布时间】:2014-12-15 19:03:34
【问题描述】:
您好,我正在制作我的第一个官方 Windows Phone 8.1 应用程序。我想知道如何在整个应用程序中添加共享命令栏。我一直这样做的方式是将xaml从每一页复制并粘贴到下一页。我觉得这是非常低效的,我只是不知道该怎么做以及在哪里添加它(如在哪个页面中)。 谢谢你的帮助。
【问题讨论】:
标签: c# windows-phone-8.1
您好,我正在制作我的第一个官方 Windows Phone 8.1 应用程序。我想知道如何在整个应用程序中添加共享命令栏。我一直这样做的方式是将xaml从每一页复制并粘贴到下一页。我觉得这是非常低效的,我只是不知道该怎么做以及在哪里添加它(如在哪个页面中)。 谢谢你的帮助。
【问题讨论】:
标签: c# windows-phone-8.1
尝试将CommandBar 添加到Application 的资源中(在App.xaml 中)。然后你可以简单地从每个页面的资源中设置它:
<Application.Resources>
<CommandBar x:Key="GlobalCommandBar"/>
</Application.Resources>
<Page
x:Class="..."
BottomAppBar={StaticResource GlobalCommandBar}>
</Page>
【讨论】:
我想到的两种方式:
a) 首先是像at MSDN 那样做——基本上你扩展Page 类并在OnLoaded 中动态添加应用程序栏。然后将应用中的所有页面更改为扩展页面。
b) 其他方法稍微复杂一些(据我记得我在 MSDN 的某个地方也看到过)并且需要更多步骤,但也许会有所帮助:
您将需要更改 Window.Current.Content 中的内容 - 在大多数应用程序中它是 Frame,让我们将其设为 Page我们常用的应用程序栏和这个页面内容将是我们新的根框架(所有应用程序页面都将放入该框架中)。在这里,我们需要在扩展页面和启动事件的代码下方更改一个小 OnLaunched 事件:
<Page x:Class="Example81.PageWithAppBar"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Frame Name="rootFrame"></Frame>
<Page.BottomAppBar>
<CommandBar>
<AppBarButton Icon="Help" Label="Ask"/>
</CommandBar>
</Page.BottomAppBar>
</Page>
// we need to expose the frame
public sealed partial class PageWithAppBar : Page
{
public Frame RootFrame { get { return rootFrame; } }
// rest ...
// app.xam.cs launched event
PageWithAppBar rootPage;
public CommandBar MyAppBar { get { return rootPage.BottomAppBar as CommandBar; } }
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
rootPage = Window.Current.Content as PageWithAppBar;
if (rootPage == null)
{
rootPage = new PageWithAppBar();
rootPage.Language = Windows.Globalization.ApplicationLanguages.Languages[0];
Window.Current.Content = rootPage;
}
if (rootPage.RootFrame.Content == null)
rootPage.RootFrame.Navigate(typeof(MainPage), e.Arguments);
Window.Current.Activate();
}
我们也不应该忘记其他事情——比如按下返回键,我们改变了一点我们的应用组织,所以这也会改变:
private void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
{
Frame frame = rootPage.RootFrame;
if (frame == null)
return;
if (frame.CanGoBack)
{
frame.GoBack();
e.Handled = true;
}
}
然后您可以正常导航到其他页面,访问我在 App 类中的属性上方公开的应用栏,您可以像这样使用它:
((App.Current as App).MyAppBar.PrimaryCommands[0] as AppBarButton).Label = "New label";
第二种方式稍微复杂一些,它还需要一些改进,并且可能在 NavigationHelper 和 SuspensionManager 中进行一些更改。上面代码的工作示例你可以find at GitHub。
【讨论】: