您的位置:知识库 » .NET技术

一步一步学Silverlight :使用样式封装控件观感

作者: TerryLee  来源: 博客园  发布时间: 2008-10-08 18:04  阅读: 13455 次  推荐: 0   原文链接   [收藏]  

 

全局样式

为了更好使样式能够重用,并且减少XAML中的代码,推荐使用全局样式。在App.xaml中定义两个样式

<Application.Resources>
    <Style x:Key="button1" TargetType="Button">
        <Setter Property="FontFamily" Value="微软雅黑"></Setter>
        <Setter Property="FontSize" Value="24"></Setter>
        <Setter Property="Foreground" Value="Green"></Setter>
        <Setter Property="Background" Value="Red"></Setter>
    </Style>
    <Style x:Key="button2" TargetType="Button">
        <Setter Property="FontFamily" Value="微软雅黑"></Setter>
        <Setter Property="FontSize" Value="24"></Setter>
        <Setter Property="Foreground" Value="Red"></Setter>
        <Setter Property="Background" Value="Red"></Setter>
    </Style>
</Application.Resources>

通过Style元素指定,需要设置唯一的一个Key,类似于CSS中的类名或者ASP.NET 2.0中Skin功能,并且通过TargetType指定该样式将使用在哪类控件上,每一个属性都用Setter来指定。在XAML中,通过StaticResource标记句法来指定具体的样式:

<Canvas Background="#46461F">
    <Button Width="200" Height="60"
            Canvas.Top="90" Canvas.Left="30" Content="提 交"
            Style="{StaticResource button1}"/>
    
    <Button Width="200" Height="60"
            Canvas.Top="90" Canvas.Left="260" Content="取 消"
            Style="{StaticResource button2}"/>
</Canvas>

相比较上面的XAML文件,现在代码已经干净多了,这使得我们可以只专注于应用程序的业务,而无需考虑它的外观(在Beta1中似乎有些属性设置后会报错)。运行后效果如下:

TerryLee_Silverlight2_0043

0
0

.NET技术热门文章

    .NET技术最新文章

      最新新闻

        热门新闻