在silverlight中有三种样式:一个是在本控件设置样式一个是在UserControl.Resources设置样式,最后一个是在App.xaml中设置样式
1.在本控件设置样式:
代码:
<Canvas Height="100" Background="Yellow" HorizontalAlignment="Left" Margin="66,93,0,0" Name="canvas1" VerticalAlignment="Top" Width="60" />
2.在UserControl.Resources设置样式
<UserControl.Resources>
<Style x:Key="canvasstyle" TargetType="Canvas">
<Setter Property="Background" Value="Blue"/>
</Style>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White">
<Canvas Height="100" Background="Yellow" HorizontalAlignment="Left" Margin="66,93,0,0" Name="canvas1" VerticalAlignment="Top" Width="60" />
<Canvas Height="100" Style="{StaticResource canvasstyle}" HorizontalAlignment="Left" Margin="201,98,0,0" Name="canvas2" VerticalAlignment="Top" Width="87" />
<Canvas Height="100" Style="{StaticResource canvasstyle}" HorizontalAlignment="Left" Margin="57,12,0,0" Name="canvas3" VerticalAlignment="Top" Width="200" />
</Grid>
在这里有的人会想,我想要设置每个控件的颜色,不是要每个都这只一遍?有没有办法一个样式设置所有相同的控件? 答案是有的。这个只需要把样式的x:Key="canvasstyle" 拿掉就行了 如下代码:
<UserControl.Resources>
<Style TargetType="Canvas">
<Setter Property="Background" Value="Blue"/>
</Style>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White">
<Canvas Height="100" Background="Yellow" HorizontalAlignment="Left" Margin="66,93,0,0" Name="canvas1" VerticalAlignment="Top" Width="60" />
<Canvas Height="100" HorizontalAlignment="Left" Margin="201,98,0,0" Name="canvas2" VerticalAlignment="Top" Width="87" />
<Canvas Height="100" HorizontalAlignment="Left" Margin="57,12,0,0" Name="canvas3" VerticalAlignment="Top" Width="200" />
</Grid>
3.在App.xaml中设置样式
只需要把刚才写的样式放在里面就行了
<Application.Resources>
<Style TargetType="Canvas" >
<Setter Property="Background" Value="Blue"/>
</Style>
</Application.Resources>