在上一遍文章中已经介绍到可以在Resources集合中定义样式,我们也可以在一个样式上引用其他的样式,这就是继承的概念,使用方法是将引用的样式放置在Style中的BaseOn属性;这里使用到的是xaml标记扩展进行设置,比如这里定义的三个样式:
<phone:PhoneApplicationPage.Resources> <Style x:Key= " tbStyle " TargetType= " TextBlock "> <Setter Property= " HorizontalAlignment " Value= " Center "></Setter> <Setter Property= " HorizontalAlignment " Value= " Center "></Setter> <Setter Property= " Foreground "> <Setter.Value> <LinearGradientBrush> <GradientStop Offset= " 0.2 " Color= " Brown "></GradientStop> <GradientStop Offset= " 0.7 " Color= " DarkBlue "></GradientStop> </LinearGradientBrush> </Setter.Value> </Setter> </Style> <Style x:Key= " fStyle " TargetType= " TextBlock "> <Setter Property= " VerticalAlignment " Value= " Bottom "></Setter> </Style> <Style x:Key= " tStyle " TargetType= " TextBlock " BasedOn= " {StaticResource tbStyle} "> <Setter Property= " VerticalAlignment " Value= " Top "></Setter> </Style> </phone:PhoneApplicationPage.Resources>
从上面代码中我们可以看到第三个样式继承了第一个样式,然后第一个样式中我们定义的垂直方向的位置,第三个也定义了垂直方向的位置,然后我们从textblock中使用第三个样式
<TextBlock x:Name= " tbContent " Text= " 显示样式 " Style= " {StaticResource tStyle} " />
效果如下:
这说明第三个样式中的属性覆盖了第一个样式中的相同的属性 ;需要注意的是,上面三个样式是有先后顺序的,即下面的可以继承上面的,但是上面的不能继承下面的,系统会提示警告,找不到你要继承的样式;那么如果这三个样式中的样式进行级联继承会出现什么情况那:代码如下:
<phone:PhoneApplicationPage.Resources> <Style x:Key= " tbStyle " TargetType= " TextBlock "> <Setter Property= " HorizontalAlignment " Value= " Center "></Setter> <Setter Property= " HorizontalAlignment " Value= " Center "></Setter> <Setter Property= " Foreground "> <Setter.Value> <LinearGradientBrush> <GradientStop Offset= " 0.2 " Color= " Brown "></GradientStop> <GradientStop Offset= " 0.7 " Color= " DarkBlue "></GradientStop> </LinearGradientBrush> </Setter.Value> </Setter> </Style> <Style x:Key= " tStyle " TargetType= " TextBlock " BasedOn= " {StaticResource tbStyle} "> <Setter Property= " VerticalAlignment " Value= " Top "></Setter> <Setter Property= " HorizontalAlignment " Value= " Left "></Setter> </Style> <Style x:Key= " fStyle " TargetType= " TextBlock " BasedOn= " {StaticResource tStyle} "> <Setter Property= " VerticalAlignment " Value= " Bottom "></Setter> </Style> </phone:PhoneApplicationPage.Resources>
然后textblock使用第三个样式
<TextBlock x:Name= " tbContent " Text= " 显示样式 " Style= " {StaticResource fStyle} " />
效果就是这样子了
所以我们可以这样总结,定义三个或更多个样式,如A,B,C 如果B继承A,C继承B,那么优先级是C>B>A,也可以这么说样式的继承是越往上优先级越低;
给大家贴两篇文章的链接,共勉: