C#Winform向WPF过渡入门(四)
            Copyright Notice: This article is an original work licensed under the CC 4.0 BY-NC-ND license.
            If you wish to repost this article, please include the original source link and this copyright notice.
            
            Source link: https://v2know.com/article/465
总目录:https://www.v2know.com/MainPage/Category/WPF
为什么说样式设计很重要?
假设你直接在Grid里面创建3个样式完全相同的按钮,
<Grid>
        <Button FontSize="20" Foreground="Red" Content="Hello" Width="100" Height="40"/>
        <Button FontSize="20" Foreground="Red" Content="Hello" Width="100" Height="40"/>
        <Button FontSize="20" Foreground="Red" Content="Hello" Width="100" Height="40"/>
</Grid>
那,这3个按钮应该会出现在同样的位置。
从结论上讲,这3个按钮是相互独立的,当你设置了大小之后,无论如何一般都会居中。
但是你如果放到容器里,这些按钮就会有序排列了:
<Grid>
        <StackPanel>
              <Button FontSize="20" Foreground="Red" Content="Hello" Width="100" Height="40"/>
              <Button FontSize="20" Foreground="Red" Content="Hello" Width="100" Height="40"/>
              <Button FontSize="20" Foreground="Red" Content="Hello" Width="100" Height="40"/>
        </StackPanel>
</Grid>
好的,按照以上代码在设计器中的展现,这样的按钮还不算美观,它是重复的,而且排列还很紧凑。
那么我们就要开始定义样式了。
定义样式
我们知道,如果你想为很多Button设置几乎一致的样式+事件的时候,你可能会对每个Button去设置,或者直接在后台写代码生成这些Button。
但是,在wpf里面,我们选择新建样式。
举个例子:
<Window.Resources>
    <Style x:Key="defaultStyle" TargetType="Button">
        <Setter Property="FontSize" Value="30"/>
    </Style>
</Window.Resources>
<Grid>
    <StackPanel>
        <Button Style="{StaticResource defaultStyle}"  Foreground="Red" Content="Hello" Width="100" Height="40"/>
    </StackPanel>
</Grid>
引用的方式就是在元素属性里面写:
Style="{StaticResource 你定义的Key的名称}"
完整基本实例:
<Window.Resources>
    <Style x:Key="defaultStyle" TargetType="Button">
        <Setter Property="FontSize" Value="30"/>
        <Setter Property="Foreground" Value="Blue"/>
        <Setter Property="Width" Value="100"/>
        <Setter Property="Height" Value="40"/>
    </Style>
</Window.Resources>
<Grid>
    <StackPanel>
        <Button Style="{StaticResource defaultStyle}"   Content="Hello"/>
        <Button Style="{StaticResource defaultStyle}"   Content="Hello"/>
        <Button Style="{StaticResource defaultStyle}"   Content="Hello"/>
    </StackPanel>
</Grid>
样式的继承:
<Style x:Key="defaultStyle" TargetType="Button" BasedOn="{StaticResource baseButtonStyle}">
下一篇:WPF样式里面的触发器使用方式
 
This article was last edited at