如何使用按钮样式作为其他按钮的模板?

How can I use a button style as a template for the other buttons?

我有一个具有以下属性的按钮:

<Grid Margin="0,0,593,0">
    <Button x:Name="btnToolbarClose" Content="X" Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" Grid.Column="1" HorizontalAlignment="Right" VerticalAlignment="Top" VerticalContentAlignment="Center"  HorizontalContentAlignment="Center" FontSize="12" FontFamily="Arial" Height="23" Width="30" Margin="0,-1,-1,0"/>
    <Button x:Name="btnToolbarMax"  Content="£" Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" Grid.Column="1" HorizontalAlignment="Right" Margin="0,-1,29,0" VerticalAlignment="Top" FontFamily="Wingdings 2" VerticalContentAlignment="Center" FontSize="12" Height="23" Width="30" />
    <Button x:Name="btnToolbarMin" Content="─" Grid.Column="1" HorizontalAlignment="Right" Margin="0,-1,59,0" VerticalAlignment="Top" VerticalContentAlignment="Bottom" HorizontalContentAlignment="Center" FontSize="14" Height="23" Width="30" >
        <Button.Style>
            <Style TargetType="{x:Type Button}">
                <Setter Property="Background" Value="{x:Null}"/>
                <Setter Property="BorderBrush" Value="{x:Null}"/>
                <Setter Property="BorderThickness" Value="0"/>
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Border Background="{TemplateBinding Background}" BorderBrush="Black" BorderThickness="0">
                                <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                            </Border>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
                <Style.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Background" Value="Red"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
    </Button>

</Grid>

现在我希望我不必为每个按钮插入这种按钮样式,而只需将这种样式用于其他具有绑定的按钮?这样我只需要编写一次这种样式并将其用于其他按钮?

重用 WPF 控件样式的一种简单方法是使用 ResourceDictionariesLink to MSDN

ResourceDictionary 添加到您的项目后,您可以通过将其添加到 XAML 的开头来引用它,如下所示:

<Window.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="./YourNewDictionary.xaml"/> // This points to the location of your dictionary.
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Window.Resources>

您可以像这样在新添加的 ResourceDictionary 中定义自定义样式:

<Style x:Key="YourButtonStyle" TargetType="Button">
    <Setter Property="Margin" Value="5"/>
    And all other customized properties....
</Style>

然后您可以像这样在您的控件中引用您的自定义样式:

<Button x:Name="YourButton" Style="{StaticResource YourButtonStyle}">

这使您可以轻松创建自定义样式,您可以在整个项目中重复使用这些样式,而不会在 XAML 文件中造成太多混乱。