在metro应用程序中创建通用AppBar

时间:2014-04-08 03:14:54

标签: c# wpf xaml

在我目前的C#WinRT MvvmLight应用程序中,我的AppBar遇到了大量重复代码。除了登录页面,我的所有页面都支持相同的AppBar。有没有办法抽象xaml代码,以及xaml.cs代码(例如,点击时的UI元素修改)

登录页面之外的任何xaml页面:

<Page.TopAppBar>
  <AppBar>
     <!-- content here -->
  </AppBar>
</Page.TopAppBar>
<Page.BottomAppBar>
  <AppBar>
     <!-- content here -->
  </AppBar>
</Page.BottomAppBar>

登录页面之外的任何xaml.cs页面:

private void UserLogout_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) {
     //First we need to find out how big our window is, so we can center to it.
     CoreWindow currentWindow = Window.Current.CoreWindow;

     //Set our background rectangle to fill the entire window
     rectBackgroundHide.Height = currentWindow.Bounds.Height;
     rectBackgroundHide.Width = currentWindow.Bounds.Width;
     rectBackgroundHide.Margin = new Thickness(0, 0, 0, 0);

     //Make sure the background is visible
     rectBackgroundHide.Visibility = Windows.UI.Xaml.Visibility.Visible;

     //Now we figure out where the center of the screen is, and we 
     //move the popup to that location.
     popupLogout.HorizontalOffset = (currentWindow.Bounds.Width / 2) - (400 / 2);
     popupLogout.VerticalOffset = (currentWindow.Bounds.Height / 2) - (150 / 2);
     popupLogout.IsOpen = true;
  }

1 个答案:

答案 0 :(得分:0)

尝试使用某个键添加资源AppBar,例如Page.Resources

<Page.Resources>
    <AppBar x:Key="MyFavoriteAppBar" x:Shared="False" ... />
</Page.Resources>

在其他来源中使用如下:

<Page.TopAppBar>
    <ContentControl Content="{StaticResource MyFavoriteAppBar}" />
</Page.TopAppBar>

<Page.BottomAppBar>
    <ContentControl Content="{StaticResource MyFavoriteAppBar}" />
</Page.BottomAppBar>

对于WPF,它为您的资源设置x:Shared="False"时效果很好,但在WinRT中没有相同的功能,它不支持此属性。

因此,需要寻找替代方案,因为可以找到其中一个选项here

示例:

<Page.Resources>
    <Style x:Name="MyFavoriteAppBar" TargetType="ContentControl">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ContentControl">
                    <AppBar ... />
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Page.Resources>

<Grid>
    <Page.TopAppBar>
        <ContentControl Style="{StaticResource MyFavoriteAppBar}" />
    </Page.TopAppBar>

    <Page.BottomAppBar>
        <ContentControl Style="{StaticResource MyFavoriteAppBar}" />
    </Page.BottomAppBar>
</Grid>

要使Click事件在您的案例中成功运作,您需要在Style中确定EventSetter,或者使用命令。