Silverlight的控件都具有MS为我们赋予的默认样式,虽然这个样式也不怎么难看,但任何产品都很少用这个默认的样式去做最后的呈现,所以我们就需要对其进行修改。


首先,根据我的了解,我想到的改变控件默认样式的方法有:一、直接在控件本身上写样式;二、定义一个公共的样式标,就像CSS一样;三、运行时样式,前面两个的样式定义好以后就生效了,而运行时样式,只有在程序运行的某一个阶段才会生效。


第一个方法很简单,我们只需要在XAML中加入希望的样式,或者通过Expression Blend在右侧属性中进行修改就可以了。

 当然,我们仍然可以通过编写代码来实现动态的控制控件的样式。

Silverlight学习笔记:改变控件的样式_控件 


第二个方法就是通过编辑外部的样式来实现改变的目的。这个方法在参考资料[​​1​​]中有详细的描述。

这里,补充一点定义样式的时候关于位置的定义,定义在程序级别 Application ,会将样式写在 App.xaml 中,如果定义在本文档的话,会在页面的上方写入。个人理解就和CSS的文档内写入和外部样式文件类同。

当我们写入 Application 时,标签是这样: <Application.Resources>

当我们写入 Document 时, 标签是这样:<UserControl.Resources>

关于样式更多的内容,可以在MSDN的资料中看到[​​2​​]。


第三个方法我是在MSDN上看到的,貌似很强大,因为“属性设置和样式可以更改控件外观的某些方面,但应用新模板可以完全更改控件的外观。尽管模板不能更改控件类型的方法和事件,但它可以更改控件的外观,具体取决于不同的状态,如按下或禁用。使用 XAML 可以定义和设置控件的模板。每个控件都有一个可以替换为自定义模板的默认模板。”。 这就是通过 ControlTemplate 来改变控件的外观。

 Cotrol Template 的设置有三种方式:

    将 Template 本地设置成内联定义的 ControlTemplate;

    将 Template 本地设置成对定义资源的 ControlTemplate 的引用;

    用 Style 设置 Template 和 定义 ControlTemplate;

    下面分别是三种方式的定义方法:


<Button Content="Button1">

  <Button.Template>

    <ControlTemplate TargetType="Button">


      <!--Define the ControlTemplate here.-->


    </ControlTemplate>

  </Button.Template>

</Button>


<StackPanel>

  <StackPanel.Resources>

    <ControlTemplate TargetType="Button" x:Key="newTemplate">


      <!--Define the ControlTemplate here.-->


    </ControlTemplate>

  </StackPanel.Resources>


  <Button Template="{StaticResource newTemplate}" Content="Button1"/>

</StackPanel>



<StackPanel>

  <StackPanel.Resources>

    <Style TargetType="Button" x:Key="newTemplate"> 

      <Setter Property="Template">

        <Setter.Value>

          <ControlTemplate TargetType="Button">


            <!--Define the ControlTemplate here.-->


          </ControlTemplate>

        </Setter.Value>

      </Setter>

    </Style>

  </StackPanel.Resources>

  <Button Style="{StaticResource newTemplate}" Content="Button1"/>

</StackPanel>




参考资料:

​1​​​、​​Silverlight2自定义样式​​。

​2​​​、​​MSDN 控件入门​

​3​​、​​使用ControlTemplate 改变现有控件外观​

4、​​创建系统控件的可重用模版​