本篇的内容较为简单,主要针对Style进行一个练习。Style简要的说就是一些属性值的集合,
作用和CSS比较像。在Silverlight2中定义Style只能同用于同种类型的Element。如下代码:
<Style x:Key="ButtonStyleTwo" TargetType="Button"> <Setter Property="FontFamily" Value="Arial" /> <Setter Property="FontSize" Value="40" /> <Setter Property="Foreground" Value="Blue" /> <Setter Property="Background"></Style>
这就是一个定义好的Style,它只能用于Button组件,看看它如何产生作用,将Style直接嵌入Button:
<Button Content="Button"> <Button.Style> <Style TargetType="Button"> <Setter Property="FontFamily" Value="Arial" /> <Setter Property="FontSize" Value="40" /> <Setter Property="Foreground" Value="Blue" /> <Setter Property="Background"> <Setter.Value> <LinearGradientBrush> <GradientStop Color="Green" Offset="0"></GradientStop> <GradientStop Color="Red" Offset="1"></GradientStop> </LinearGradientBrush> </Setter.Value> </Setter> </Style> </Button.Style></Button>
当然也可以通过Resource的方式来设置Style,分别设置了两个Style:ButtonStyleOne、ButtonStyleTwo,
ButtonStyleOne设置为默认Style,ButtonStyleTwo用于在点击Button后切换Style。
XAML Code:
<UserControl x:Class="SilverlightTest.Page" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="400"> <UserControl.Resources> <Style x:Key="ButtonStyleOne" TargetType="Button"> <Setter Property="FontFamily" Value="Georgia" /> <Setter Property="FontSize" Value="40" /> <Setter Property="Foreground" Value="SlateGray" /> <Setter Property="Background"> <Setter.Value> <LinearGradientBrush> <GradientStop Color="Blue" Offset="0"></GradientStop> <GradientStop Color="Yellow" Offset="1"></GradientStop> </LinearGradientBrush> </Setter.Value> </Setter> </Style> <Style x:Key="ButtonStyleTwo" TargetType="Button"> <Setter Property="FontFamily" Value="Arial" /> <Setter Property="FontSize" Value="40" /> <Setter Property="Foreground" Value="Pink" /> <Setter Property="Background"> <Setter.Value> <LinearGradientBrush> <GradientStop Color="Green" Offset="0"></GradientStop> <GradientStop Color="Red" Offset="1"></GradientStop> </LinearGradientBrush> </Setter.Value> </Setter> </Style> </UserControl.Resources> <StackPanel x:Name="LayoutRoot" Background="White"> <Button x:Name="TestButton" Content="A Customized Button"
Style="{StaticResource ButtonStyleOne}" Click="Button_Click"></Button> </StackPanel> </UserControl>
用C#来切换Sytle,如下代码:
private void Button_Click(object sender, RoutedEventArgs e) { //切换Style:ButtonStyleTwo TestButton.Style = this.Resources["ButtonStyleTwo"] as Style; //修改Button文字
TestButton.Content = "Style Changed"; }
实例Demo效果(感谢GWPBrian指导SL嵌入cnblogs方法):
本例参考自《Pro Silverlight 2 in C# 2008》CHAPTER 11 ■ STYLES, TEMPLATES, AND CUSTOM CONTROLS