silverlight(二)樣式

在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>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章