就像网页配合CSS一样,XAML元素结合Style可以使Silverlight页面变得绚丽多彩。Silverlight的最大吸引力就是无论你想做什么格式的,什么效果的页面你都可以实现,绝对没有不可能。想使页面变得绚丽,简单Style就可以,想使页面变得特性十足或是千变万化,那就学好模板,想要使页面动起来,Storyboard可以帮助你。
样式(Style)、模板(Template)很少直接定义在控件或者页面元素内部,一般都定义在外部资源文件中,这样不但便于维护,更便于重用。什么叫资源,凡是放在页面或控件Resource节点下,或是放在独立资源文件中的ResourceDictionary节点下的全是资源,Style和Template都属于资源。
将Style定义在App.xaml文件中,看下面的代码
  1. <Application

  2. x:Class="StyleAndTemplate.App"

  3. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

  4. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

  5. xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"

  6. xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone">
  7. <!--Application Resources-->

  8. <Application.Resources>

  9. <Style x:Key="MyTextBlock" TargetType="TextBlock">

  10. <Setter Property="FontSize" Value="50"/>

  11. <Setter Property="Foreground" Value="Blue"/>

  12. </Style>

  13. </Application.Resources>
  14. <Application.ApplicationLifetimeObjects>

  15. <!--Required object that handles lifetime events for the application-->

  16. <shell:PhoneApplicationService

  17. Launching="Application_Launching" Closing="Application_Closing"

  18. Activated="Application_Activated" Deactivated="Application_Deactivated"/>

  19. </Application.ApplicationLifetimeObjects>
  20. </Application>
复制代码
如上面的代码,只要将Style写在Application.Resources节点下
将Style定义在单独的资源文件中,首先需要在项目中添加一个xaml后缀的文件(MyResource.xaml),在文件中写入如下代码

  1. <ResourceDictionary

  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

  4. xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"

  5. xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone">



  6. <Style x:Key="MyTextBlock" TargetType="TextBlock">

  7. <Setter Property="FontSize" Value="50"/>

  8. <Setter Property="Foreground" Value="Blue"/>

  9. </Style>

  10. </ResourceDictionary>
复制代码
看上面的文件,ResourceDictionary节点写添加i几个命名空间,前三个是必须的,第一个字默认命名空间,资源的象征,第二个用来定义唯一标示,没有他,无法定义和引用资源,第三个是引入控件,用于填入TargetType属性(下面说明他的重要性)。定义好了资源文件还需要在App.xaml文件中注册该资源文件,在App.xaml中写入如下代码

  1. <Application.Resources>

  2. <ResourceDictionary>

  3. <ResourceDictionary.MergedDictionaries>

  4. <ResourceDictionary Source="MyResource.xaml"/>

  5. </ResourceDictionary.MergedDictionaries>

  6. </ResourceDictionary>

  7. </Application.Resources>
复制代码
这样在页面中,就可以使用该Style了,MainPage.xaml中添加一个TextBlock,并给他添加样式,写法:<TextBlock Text="MyText" Style="{StaticResource MyTextBlock}"/>,StaticResource是静态资源的标示,所有定义在页面级、App.xaml中或者定义在外部资源中的都是静态资源,还有一个RelativeSource,是定义在某元素内部时,父子控件之间相互使用的资源,没人使用,不用研究。
上述两种方式运行效果是一样的,如下图所示
2012-5-2 18:15:52 上传
下载附件 (8.91 KB)

相关文章:

  • 2022-12-23
  • 2021-08-26
  • 2021-11-17
  • 2021-08-28
  • 2022-12-23
猜你喜欢
  • 2021-06-23
  • 2021-08-18
  • 2021-07-08
相关资源
相似解决方案