本文为原创文,难免会有一些小得瑕疵,敬请谅解。
所有示例均是博主测试过的,如有转载请标明出处,谢谢。
在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>