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

Pal*_*mar 0 c# wpf resourcedictionary

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

设计:

<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>
Run Code Online (Sandbox Code Playgroud)

资源:

<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>
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

nko*_*hvt 7

您将两个相同的内容设置为两个不同的控件.问题是Setter.Value中的StackPanel不能有两个Parent,因此将应用最后一次使用.您可以使用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>
Run Code Online (Sandbox Code Playgroud)