控件的Style前面几篇博客有说过了,不过那里展示的是把Style嵌入到当前的Xaml里面,这里显示怎么使用资源字典来外置一个Style的文件,就像CSS一样引用使用。
首先新建一个XAML作为资源字典
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style x:Key="WhiteBt" TargetType="Button">
<Setter Property="Background" Value="Blue"></Setter>
</Style>
</ResourceDictionary>
在这个XAML里面声明了Button的Style,也就是把背景颜色改为蓝色。下面看看怎么引用这个文件。
下面是要设置Style的xaml
<phone:PhoneApplicationPage
x:Class="StyleTask.MainPage"
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"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<Grid HorizontalAlignment="Left" Height="768" VerticalAlignment="Top" Width="480">
<Grid.Resources>
<ResourceDictionary Source="Res.xaml"></ResourceDictionary>
</Grid.Resources>
<Button Style="{StaticResource WhiteBt}" Content="Button" HorizontalAlignment="Left" Margin="162,307,0,0" VerticalAlignment="Top"/>
</Grid>
</phone:PhoneApplicationPage>
可以看到Button的背景颜色被设置为蓝色了。通过这个方法把Style外置到一个文件需要的时候再引用是一个很不错的选择。