WPF - 为多个控件设置相同的样式

WPF - Set the same style to multiple controls

是否可以为多个控件设置相同的样式? 我尝试了以下方式。但是第一个按钮样式应用不正确,第二个样式应用正常。

设计:

<StackPanel Orientation="Horizontal">
    <TextBlock Foreground="White" Margin="0,0,5,0">1st Button</TextBlock>
    <Button Style="{StaticResource ViewButton}" />
    <TextBlock Foreground="White" Margin="25,0,5,0">2nd Button</TextBlock>
    <Button Style="{StaticResource ViewButton}" />
</StackPanel>

资源:

<Style x:Key="ViewButton" TargetType="Button" BasedOn="{StaticResource ButtonStyle}">
    <Setter Property="Content">
        <Setter.Value>
            <StackPanel Orientation="Horizontal">
                <Image Source="/Images/View.png" Stretch="None" Width="24" Height="24" />
                <TextBlock Margin="5,0,0,0" HorizontalAlignment="Center" VerticalAlignment="Center" FontWeight="Bold">View</TextBlock>
            </StackPanel>
        </Setter.Value>
    </Setter>
    <Setter Property="Padding" Value="2,0,10,0"/>
</Style>

您为两个不同的控件设置了两次相同的内容。问题是 Setter.Value 中的 StackPanel 不能有两个父级,因此将应用最后一次使用。您可以使用 ContentTemplate 使其工作:

<Style x:Key="ViewButton" TargetType="Button" BasedOn="{StaticResource ButtonStyle}">
    <Setter Property="ContentTemplate">
        <Setter.Value>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <Image Source="/Images/View.png" Stretch="None" Width="24" Height="24" />
                    <TextBlock Margin="5,0,0,0" HorizontalAlignment="Center" VerticalAlignment="Center" FontWeight="Bold">View</TextBlock>
                </StackPanel>
            </DataTemplate>
        </Setter.Value>
    </Setter>
    <Setter Property="Padding" Value="2,0,10,0"/>
</Style>

.... .... ....

您必须在 as Button 中提及 TargetType。并且您需要按照我写的样式名称编写样式 属性。

希望这对你有用..

谢谢