如何在WPF控件中应用样式?

Ami*_*mit 9 wpf

我是WPF的初学者,需要你的帮助.

问题:我在表单上有4个按钮,需要在2对按钮上应用2种不同的样式.

我们有什么办法可以实现这个目标吗?

请尽可能提供样品......

提前致谢...

Ben*_*ier 15

您可以定义命名样式,然后根据需要将它们显式分配给任何控件.这是造型按钮的入门:WPF入门:按钮控制第2部分 - 基本样式

这是一个例子:

<Window x:Class="WpfButtonStyling.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="250" Width="400">
    <Window.Resources>
        <Style x:Key="ButtonStyle1" 
               TargetType="{x:Type Button}">
            <Setter Property="Foreground"
                    Value="Red" />
            <Setter Property="Margin"
                    Value="10" />
        </Style>
        <Style x:Key="ButtonStyle2" 
               TargetType="{x:Type Button}">
            <Setter Property="Foreground"
                    Value="Blue" />
            <Setter Property="Margin"
                    Value="10" />
        </Style>
    </Window.Resources>

    <Grid>
        <StackPanel>
            <Button x:Name="FirstButton"
                    Content="First!"
                    Style="{StaticResource ButtonStyle1}"/>
            <Button x:Name="SecondButton"
                    Content="Second"
                    Style="{StaticResource ButtonStyle2}" />
        </StackPanel>
    </Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)