Silverlight之添加全局样式

本文为原创文,难免会有一些小得瑕疵,敬请谅解。
所有示例均是博主测试过的,如有转载请标明出处,谢谢。
在Asp.Net中,我们可以使用Css+Div来控制样式,在Silverlight中我们也可以使用全局样式。
当我们新建一个Silverlight项目时,会发现里面自带一个App.Xaml文件,此文件格式如下:

<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             x:Class="RemoveTextBoxBorder.App"
             >
    <Application.Resources>
    </Application.Resources>
</Application>

一般情况中,我们可以在这个文件中直接添加自己定义样式,例如:

<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             x:Class="SilverlightTest.App"
             >
    <Application.Resources>
        <Style x:Key="ButtonStyle" TargetType="Button">
            <Setter Property="Width" Value="100" />
            <Setter Property="Foreground" Value="Blue" />
            <Setter Property="BorderThickness" Value="4,4,4,4" />
        </Style>
    </Application.Resources>
</Application>

然后在控件中引入此样式:

<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" Height="300">
    <Grid x:Name="LayoutRoot" Background="White">
        <Button Content="Button" Height="75" Style="{StaticResource ButtonStyle}"/>     
    </Grid>
</UserControl>

但是,有时我们做程序时,为了使用样式更加清晰,想要把样式单独存在一个文件夹中,这时我们需要使用资源字典。
首先,在项目中添加一个文件夹,名字叫Styles。
然后,点击右键添加新建项,选择Silverlight资源字典,名为BaseStyle.Xaml

在资源字典中,添加你所需要的样式,例如:

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>
<Style x:Key="TextBoxStyle" TargetType="TextBox">
<Setter Property="Padding" Value="3,0,0,0"></Setter>
<Setter Property="VerticalAlignment" Value="Top"></Setter>
<Setter Property="HorizontalAlignment" Value="Left"></Setter>
<Setter Property="Width" Value="100"></Setter>
</Style>
</ResourceDictionary>

然后,在App.Xaml文件中,引入此资源字典:

  <Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Styles/BaseStyle.xaml"></ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>

最后,我们就可以在控件中引入此样式:

<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" Height="300">
    <Grid x:Name="LayoutRoot" Background="White">
      <TextBox Name="txtMoney" Margin="5,4,0,0" Style="{StaticResource TextBoxStyle}"/>  
    </Grid>
</UserControl>





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值