2012-04-12 89 views
2

我正在爲我的應用程序創建一個資源字典,我將在其中有一些「圖標+文本」按鈕。因爲他們看起來都一樣(除了圖標和文本),我創建了一個通用的風格作爲基礎,其他:使用泛型作爲基礎vs自定義用戶控件

<!-- Generic ActionButtonStyle --> 
<Style x:Key="ActionButtonStyle" TargetType="{x:Type Button}"> 
    <!-- some setter properties --> 
    <Setter Property="ContentTemplate" Value="{DynamicResource ButtonDataTemplate}"/> 
</Style> 
<DataTemplate x:Key="ButtonDataTemplate"> 
    <Grid> 
     <Grid.ColumnDefinitions> 
      <ColumnDefinition Width="24" /> 
      <ColumnDefinition Width="*" /> 
     </Grid.ColumnDefinitions> 
     <Image Source="{Binding Source}" 
       Stretch="Uniform" 
       Grid.Column="0" 
       Margin="2"/> 
     <TextBlock Text="{Binding text}" 
        TextWrapping="Wrap" 
        Grid.Column="1" 
        Margin="2" 
        VerticalAlignment="Center"/> 
    </Grid> 
</DataTemplate> 

而且我對圖標的一些圖片:

<!-- Icons --> 
    <ImageSource x:Key="textToSpeech">Images/GreyIcons/TextToSpeech.png</ImageSource> 
    <ImageSource x:Key="play">Images/GreyIcons/Play.png</ImageSource> 
    <ImageSource x:Key="playSound">Images/GreyIcons/PaySound.png</ImageSource> 
    . 
    . 
    . 
    . 
    <ImageSource x:Key="group">Images/GreyIcons/Goup1.png</ImageSource> 

而且我想爲每個按鈕(對應於每個圖標)創建單獨的樣式。類似這樣的:

<!-- Specific ActionButtonStyles --> 
<Style x:Key="TextToSpeechButtonStyle" TargetType="{x:Type Button}" BasedOn="{StaticResource ActionButtonStyle}"> 
    <Setter Property="Content"> 
     <Setter.Value> 
      <Image Source="{StaticResource textToSpeech}" 
     </Setter.Value> 
    </Setter> 
</Style> 

我知道這不起作用。我應該怎麼做?我應該爲通用按鈕創建一個自定義用戶控件嗎?該文本將綁定到我的模型中的一個對象,命令(對一個動作)也一樣。

回答

1

你正在尋找什麼的例子似乎缺失,但似乎你可能正在尋找「BasedOn」 - 它允許你繼承,但仍然覆蓋以前定義的風格。你可以這樣實現:

<Style x:Key="MyButtonStyle" BasedOn="{StaticResource ActionButtonStyle}"> 
    <Setter.../> 
</Style> 
+0

我知道,但我應該使用哪一個setter? (有些代碼丟失了,我剛剛更新了我的問題) – Joana 2012-04-12 09:20:12

1

你需要從按鈕創建一個派生類,添加兩個新的DependancyProperties。他們將被稱爲像文字和圖像源。您的派生類也會按照您的指示設置ContentTemplate。這個ContentTemplate會綁定Text和ImageSource的依賴屬性。

然後,您可以在XAML像這樣創建自定義的控制......

<app:CustomButton Text="Play" Source="{Binding play}"/> 

...但如果你想同一個按鈕一遍又一遍,你可以創建一個應用到的CustomButton風格並根據需要設置這兩個屬性。