2

I'm creating a resource dictionary to my application, where I'll have some "icon+text" buttons. Since they will all look the same (except for the icon and the text), I've created a generic style to serve as base to the others:

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

And I have some images for the icons:

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

And I'd like to create individual styles for each button (corresponding to each icon). Something like this:

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

I know that this doesn't work.. How should I do it? Should I create a custom user control for the generic button? The text will be binding to an object in my Model, and so will the command (to an action).

4

2 回答 2

1

您正在寻找的示例似乎丢失了,但您似乎正在寻找“BasedOn” - 它允许您继承,但仍然覆盖先前定义的样式。你可以像这样实现它:

<Style x:Key="MyButtonStyle" BasedOn="{StaticResource ActionButtonStyle}">
  <Setter.../>
</Style>
于 2012-04-12T01:51:46.010 回答
1

您需要从添加两个新 DependancyProperties 的 Button 创建派生类。它们将被称为 Text 和 ImageSource 之类的东西。您的派生类还将按照您的指示设置 ContentTemplate。此 ContentTemplate 将绑定 Text 和 ImageSource 依赖属性。

然后,您可以像这样在 XAML 中创建自定义控件...

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

...但是如果您一遍又一遍地想要同一个按钮,您可以创建一个应用于 CustomButton 的样式并根据需要设置这两个属性。

于 2012-04-12T02:19:02.160 回答