2016-01-19 52 views
0

是否可以将相同样式设置为多个控件? 我尝试了以下方法。但1st Button风格没有正确应用,在第二种风格中应用得很好。WPF - 将相同样式设置为多个控件

设计:

<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> 

enter image description here

+1

你不应该使用的模板,而不是内容的风格? –

+0

@JanneMatikainen是的,我之前使用过Template,但我必须使用ContentTemplate才能使其工作。最后nkoniishvt的解决方案帮助了我。 –

回答

7

你设定两次相同内容到两个不同的控件。问题是Setter.Value中的StackPanel不能有两个Parents,所以最后一次使用将被应用。您可以使用的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> 
+0

谢谢。在我尝试而不是之前。感谢您指出我在正确的方式:) –

0

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

你就不得不提到的TargetType在为按钮。你需要按照我写的样式名称编写样式属性。

希望这会为你工作..

感谢

+0

<样式的TargetType = “{x:Type按钮}” X:键= “测试”> .... .... ....

相关问题