给控件添加一个样式

 在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> 

程序运行的显示效果如下:

 

 

 

 

 

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