样式(Style)、模板(Template)很少直接定义在控件或者页面元素内部,一般都定义在外部资源文件中,这样不但便于维护,更便于重用。什么叫资源,凡是放在页面或控件Resource节点下,或是放在独立资源文件中的ResourceDictionary节点下的全是资源,Style和Template都属于资源。
将Style定义在App.xaml文件中,看下面的代码
- <Application
- x:Class="StyleAndTemplate.App"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
- xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone">
- <!--Application Resources-->
- <Application.Resources>
- <Style x:Key="MyTextBlock" TargetType="TextBlock">
- <Setter Property="FontSize" Value="50"/>
- <Setter Property="Foreground" Value="Blue"/>
- </Style>
- </Application.Resources>
- <Application.ApplicationLifetimeObjects>
- <!--Required object that handles lifetime events for the application-->
- <shell:PhoneApplicationService
- Launching="Application_Launching" Closing="Application_Closing"
- Activated="Application_Activated" Deactivated="Application_Deactivated"/>
- </Application.ApplicationLifetimeObjects>
- </Application>
将Style定义在单独的资源文件中,首先需要在项目中添加一个xaml后缀的文件(MyResource.xaml),在文件中写入如下代码
- <ResourceDictionary
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
- xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone">
- <Style x:Key="MyTextBlock" TargetType="TextBlock">
- <Setter Property="FontSize" Value="50"/>
- <Setter Property="Foreground" Value="Blue"/>
- </Style>
- </ResourceDictionary>
- <Application.Resources>
- <ResourceDictionary>
- <ResourceDictionary.MergedDictionaries>
- <ResourceDictionary Source="MyResource.xaml"/>
- </ResourceDictionary.MergedDictionaries>
- </ResourceDictionary>
- </Application.Resources>
上述两种方式运行效果是一样的,如下图所示
2012-5-2 18:15:52 上传
下载附件 (8.91 KB)