2012-01-24 45 views
3

我正在使用按钮在Wpf C#应用程序。 我宣布一个样式为这些按钮:全球按钮的动态风格与每个按钮不同的图像

<Style x:Key="ButtonStyle" TargetType="{x:Type Button}"> 
     <Setter Property="Template"> 
      <Setter.Value> 
       <ControlTemplate TargetType="{x:Type Button}"> 
        <Grid Margin="0" Width="100" Height="60" > 
         //some more code here that sets color and stuff 
          <ContentPresenter HorizontalAlignment="Stretch" /> 
          <Image Source="Images/search_48.png"/> 
        //some more code here (triggers) 
      </Setter.Value> 
     </Setter> 
    </Style> 

我想这种风格应用到我的窗口所有的按钮,但图像是不同的。

我可以通过复制代码并将每个按钮设置为自己的样式来创建很多样式,但仅更改图像,但我不希望此重复。

我设置的按钮样式是这样的:

<Button x:Name="buttonName" 
     Style="{DynamicResource ButtonStyle}" 
     Content="button text"> 

正如我所说的,我有很多按钮,这样,我希望他们都具有相同的风格,但改变图像源在此风格每个按钮。

有没有办法做到这一点,而不是用每个按钮的不同名称创建相同的样式?

回答

3

为什么你不把图像放在按钮中而不是样式中。

<Button x:Name="buttonName" Style="{DynamicResource ButtonStyle}" > 
    <Image Source="Images/search_48.png"/> 
</Button> 

则样式应该是这样的:

<Style x:Key="ButtonStyle" TargetType="{x:Type Button}"> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="{x:Type Button}"> 
       <Grid Margin="0" Width="100" Height="60" > 
        //some more code here that sets color and stuff 
         <ContentPresenter HorizontalAlignment="Stretch" /> 
       //some more code here (triggers) 
     </Setter.Value> 
    </Setter> 
</Style> 

UPDATE:如果您有文字和图片使用堆栈面板:

<Button x:Name="buttonName" Style="{DynamicResource ButtonStyle}" > 
    <StackPanel Orientation="Horizontal"> 
     <Image Source="Images/search_48.png" Stretch="None" /> 
     <TextBlock>text</TextBlock> 
    </StackPanel> 
</Button> 

使用堆叠面板将允许你要么为你的按钮布局使用垂直或水平方向。然后可以使用按钮内的边距来定位文本和图像。

+0

它提供了一个错误“属性‘内容’设置不止一次。\t” – Programer

+0

即使它的工作,在风格上更容易把我想要(找到它的网格)的图像 – Programer

+0

这是奇。你用你的按钮放文本吗? –