2013年4月28日 星期日

[W8App] Add AppBar (1)

在程式中加入AppBar最基本的方法,是在MainPage.xaml的<Page></Page>區間中加入以下程式。

   1: <Page.BottomAppBar>
   2:   <AppBar>
   3:     <StackPanel Orientation="Horizontal">
   4:     </StackPanel>
   5:   </AppBar>
   6: </Page.BottomAppBar>

Page.BottomAppBar如字面所示,會在應用程式下方嵌入AppBar。除了BottomAppBar以外,也有TopAppBar可產生嵌在應用程式上部顯示的appbar。為了GUI排版的需求,通常不會直接在AppBar中加入元件,而是先放置StackPanel後,再把元件放置於StackPanel中,以其有一致的風格。

如果要有更複雜的風格變化,就加入Grid來幫忙吧,像下面的方式可以在AppBar常見的左邊和右邊都有元件形式。


   1: <AppBar>
   2:     <Grid>
   3:         <StackPanel HorizontalAlignment="Left" Orientation="Horizontal">
   4:         </StackPanel>
   5:         <StackPanel HorizontalAlignment="Right" Orientation="Horizontal">
   6:         </StackPanel>
   7:     </Grid>
   8: </AppBar>

系統其實已經提供不少預設的AppBarButton給我們使用,只是需要把他們「打開」而已。

開啟專案的Common / StandardStyles.xaml 檔案,可以發現有一大段的程式被隱藏在下面這段敘述之後:

<!-- 
Standard AppBarButton Styles for use with Button and ToggleButton

An AppBarButton Style is provided for each of the glyphs in the Segoe UI Symbol font.
Uncomment any style you reference (as not all may be required).
-->



這裡面包含了各種AppBarButton的圖片文字,關於這些AppBarButton的icon圖片可參考MSDN的AppBar button style images這篇文章。

我選擇了PlayAppBarButtonStyle來測試,在StandardStyles.xaml中把PlayAppBarButtonStyle的註釋區間取消,程式會像這樣:


   1: <Style x:Key="PlayAppBarButtonStyle" TargetType="ButtonBase" BasedOn="{StaticResource AppBarButtonStyle}">
   2:     <Setter Property="AutomationProperties.AutomationId" Value="PlayAppBarButton"/>
   3:     <Setter Property="AutomationProperties.Name" Value="Play"/>
   4:     <Setter Property="Content" Value="&#xE102;"/>
   5: </Style>

然後在MainPage.xaml的AppBar中加入Button元件,並指定其風格為"{StaticResource PlayAppBarButtonStyle}",程式會像這樣:


   1: <AppBar>
   2:     <StackPanel HorizontalAlignment="Left" Orientation="Horizontal">
   3:         <Button x:Name="PlayBtn" Style="{StaticResource PlayAppBarButtonStyle}"/>
   4:     </StackPanel>
   5: </AppBar>

在VS2012中看到的結果會長的像這樣

clip_image001

UI完成後別忘了處理使用者按下PlayButton的事件,除了直接在.xaml中寫入程式碼外,我比較推廌透過VS2012的Properties來加入事件,可以直接在程式中產生相對應的程式碼,省去不少Key in的工作。

clip_image002

clip_image003

如果對自製AppBar button有與趣的也可參考MSDN的Quickstart: Styling app bar buttons

沒有留言:

張貼留言