Silverlight中Setter作用及用法

来源:互联网 发布:php 变量前加@ 编辑:程序博客网 时间:2024/06/05 02:45

===Setter作用及用法===

*它的作用是将值应用于 Style 中的属性。

*一个 Style 包含一个或多个 Setter 对象的集合。每个 Setter 都有一个 Property 和一个 Value。Property 是此样式所应用于的元素的属性。Value 是应用于该属性的值。
*必须在 Setter 上同时指定 Property 和 Value 属性,否则将引发异常。
*下面的示例创建两个样式:一个用于 TextBlock,一个用于 TextBox。TextBlock 的样式会设置 Foreground、FontSize 和 VerticalAlignment 属性。TextBox 的样式会设置 Width、Height、Margin、Background 和 FontSize 属性。每个样式将分别应用于控件的两个实例,以便为每个 TextBlock 和 TextBox 创建相同的外观。

 

<StackPanel>
  <StackPanel.Resources>
    <!--Create a Style for a TextBlock to specify that the
              Foreground equals Navy, FontSize equals 14, and
              VerticalAlignment equals Botton.-->
    <Style TargetType="TextBlock" x:Key="TextBlockStyle">
      <Setter Property="Foreground" Value="Navy"/>
      <Setter Property="FontSize" Value="14"/>
      <Setter Property="VerticalAlignment" Value="Bottom"/>
    </Style>

    <!--Create a Style for a TextBlock that specifies that
              the Width is 200, Height is 20, Margin is 4,
              Background is LightBlue, and FontSize is 14.-->
    <Style TargetType="TextBox" x:Key="TextBoxStyle">
      <Setter Property="Width" Value="200"/>
      <Setter Property="Height" Value="30"/>
      <Setter Property="Margin" Value="4"/>
      <Setter Property="FontSize" Value="14"/>
      <Setter Property="Background">
        <Setter.Value>
          <LinearGradientBrush StartPoint="0,0.5" EndPoint="1,0.5">
            <GradientStop Color="White" Offset="0.0"/>
            <GradientStop Color="LightBlue" Offset="0.5"/>
            <GradientStop Color="Navy" Offset="1"/>
          </LinearGradientBrush>
        </Setter.Value>
      </Setter>
    </Style>
  </StackPanel.Resources>

  <!--Apply the TextBlockStyle and TextBoxStyle to each
          TextBlock and TextBox, respectively.-->
  <StackPanel Orientation="Horizontal">
    <TextBlock Style="{StaticResource TextBlockStyle}">
              First Name:
          </TextBlock>
    <TextBox Style="{StaticResource TextBoxStyle}"/>
  </StackPanel>
  <StackPanel Orientation="Horizontal">
    <TextBlock Style="{StaticResource TextBlockStyle}">
              Last Name:
          </TextBlock>
    <TextBox Style="{StaticResource TextBoxStyle}" 
                   Margin="6,4,4,4"/>
  </StackPanel>
</StackPanel>