2012-01-24 47 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

這是奇。你用你的按鈕放文本嗎? –