[Win8]Windows8开发笔记(七):页面样式的相关介绍

Windows8下的页面样式和CSS非常相似,所有的属性都可以当作样式使用,没有单独的样式。

1.内联样式:就是直接修改控件的样式。

2.页面样式:在根节点下增加

<Page.Resources>

    <Style>

        <Setter></Setter>

    </Style>

</Page.Resources>

下面新建一个项目TestStyle来看一下。

拖拽三个Button做实验:

        <Button Content="Button" HorizontalAlignment="Center" Margin="0,0,0,-100" VerticalAlignment="Center"/>
        <Button Content="Button" HorizontalAlignment="Center" Margin="0,0,0,100" VerticalAlignment="Center"/>
        <Button Content="Button" HorizontalAlignment="Center" Margin="0,0,0,0" VerticalAlignment="Center"/>


一种写法是在xaml文件里挨个写上Foreground="xxxxx"这种的,但是以后如果修改每次都要对其进行修改,如果三四个按钮还好办,如果是七八十个,那工作量估计就可观了。


所以我们需要像CSS一样指定样式。

现在在xaml里面新建一个样式:

<Page.Resources>
        <!--这个样式用于button类型的控件,必须强制-->
        <Style TargetType="Button">
            <Setter Property="Foreground" Value="Red"/>
        </Style>
    </Page.Resources>


可以看到,button的字体已经变成了红色:

当然Setter也可以设置很多次。

Resources是配置的一个属性,上面的操作相当于设定配置类的Resouces属性。

那如果想要某两个button变成紫色怎么操作呢?

可以给这个Style样式起个名字:key,然后样按钮使用这个样式即可。

比如添加一个Style:

<Style TargetType="Button">
            <Setter Property="Foreground" Value="Red"/>
        </Style>
        <Style TargetType="Button" x:Name="Style1">
            <Setter Property="Foreground" Value="Blue"/>
        </Style>


那么Button在调用Style的时候也要注明Resource的key值:

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <Button Content="Button" HorizontalAlignment="Center" Margin="0,0,0,-100" VerticalAlignment="Center"/>
        <Button Content="Button" HorizontalAlignment="Center" Margin="0,0,0,100" VerticalAlignment="Center"/>
        <Button Style="{StaticResource Style1}" Content="Button" HorizontalAlignment="Center" Margin="0,0,0,0" VerticalAlignment="Center"/>
    </Grid>


这样效果就是这样的:



和CSS一样,除了这样在xaml里面直接定义,也可以定义资源字典来调用样式。

新建一个文件,选择  资源字典:



 默认的样式文件内容如下:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:TestStyle">
    
</ResourceDictionary>


我们可以在里面添加自定义的样式,比如Style2:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:TestStyle">
    <Style TargetType="Button" x:Key="Style2">
        <Setter Property="Background" Value="White" />
    </Style>
</ResourceDictionary>


那么如何在xaml中引用样式呢?

如下代码可以实现:

 <Page.Resources>
        <ResourceDictionary Source="MyDictionary.xaml"></ResourceDictionary>
    </Page.Resources>
    



这样就可以使用在MyDictionary中定义的样式们了:




当然也可以去App.xml,或者在StantardStyles.xaml里面,这样所有的页面都可以使用StandardStyles里面的样式了。

原文地址:https://www.cnblogs.com/javawebsoa/p/2989571.html