Silverlight 2的Style練習(xí)
本篇的內(nèi)容較為簡單,主要針對(duì)Silverlight 2的Style進(jìn)行一個(gè)練習(xí)。Style簡要的說就是一些屬性值的集合,
作用和CSS比較像。在Silverlight 2中定義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>
這就是一個(gè)定義好的Style,它只能用于Button組件,看看它如何產(chǎn)生作用,將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>
當(dāng)然也可以通過Resource的方式來設(shè)置Style,分別設(shè)置了兩個(gè)Style:ButtonStyleOne、ButtonStyleTwo,
ButtonStyleOne設(shè)置為默認(rèn)Style,ButtonStyleTwo用于在點(diǎn)擊Button后切換Style。
Silverlight 2的Style練習(xí):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";
- }
以上就是Silverlight 2的Style練習(xí)。
【編輯推薦】