給控件添加一個樣式

 在win8開發中,我們的界面上有很多控件,比如按鈕和文本,很多時候爲了界面的統一,這些控件都會具有統一的風格,如果我們不對控件設定一些自定義的風格的話,將會使用系統默認的風格。

下面來講一下,如何給一個文本設定一種風格,並將它應用到其他的文本上,要使我們設定的風格在其他的xaml文件中也能夠用到,我們可以在App.xaml文件中進行定義。如下:

  1. <Application 
  2.     x:Class="stylecontrol.App" 
  3.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
  4.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
  5.     xmlns:local="using:stylecontrol" 
  6.     RequestedTheme="Light"> 
  7.  
  8.     <Application.Resources> 
  9.         <ResourceDictionary> 
  10.             <ResourceDictionary.MergedDictionaries> 
  11.  
  12.                 <!--  
  13.                     Styles that define common aspects of the platform look and feel 
  14.                     Required by Visual Studio project and item templates 
  15.                  --> 
  16.                 <ResourceDictionary Source="Common/StandardStyles.xaml"/> 
  17.             </ResourceDictionary.MergedDictionaries> 
  18.             <Style x:Key="BigGreenTextStyle" TargetType="TextBlock"> 
  19.                 <Setter Property="Foreground" Value="Green"/> 
  20.                 <Setter Property="FontSize" Value="36"/> 
  21.                 <Setter Property="FontFamily" Value="{StaticResource ContentControlThemeFontFamily}"/> 
  22.                 <Setter Property="TextTrimming" Value="WordEllipsis"/> 
  23.                 <Setter Property="TextWrapping" Value="Wrap"/> 
  24.                 <Setter Property="Typography.StylisticSet20" Value="True"/> 
  25.                 <Setter Property="Typography.DiscretionaryLigatures" Value="True"/> 
  26.                 <Setter Property="Typography.CaseSensitiveForms" Value="True"/> 
  27.             </Style> 
  28.  
  29.         </ResourceDictionary> 
  30.     </Application.Resources> 
  31. </Application> 

這裏說明我們要設定風格的目標控件是:"TextBlock"風格的名稱是:"BigGreenTextStyle"這樣我們就可以將此風格應用到其他xaml文件中的 TextBlock控件當中去了。如下:

  1. <StackPanel Grid.Row="1" Margin="120,30,0,0"> 
  2.     <TextBlock Text="What's your name?" Style="{StaticResource BigGreenTextStyle}"/> 
  3.     <StackPanel Orientation="Horizontal" Margin="0,20,0,20"> 
  4.         <TextBox x:Name="nameInput" Width="300" HorizontalAlignment="Left"/> 
  5.         <Button Content="Say &quot;Hello&quot;" Click="button_click"/> 
  6.     </StackPanel> 
  7.     <TextBlock x:Name="greetingOutput" Style="{StaticResource BigGreenTextStyle}"/> 
  8. </StackPanel> 

程序運行的顯示效果如下:

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章