-1

I am trying to style a few buttons in C# WPF. These buttons should all have different background images displaying different icons. Is it possible to set the same buttonstyle on all buttons and then specify each unique icon. This is the style I am using:

<Style TargetType="Button" x:Key="ButtonStyle">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="Button">
        <Grid>
          <Ellipse Fill="SlateGray"/>
          <Ellipse Margin="2">
            <Ellipse.Fill>
              <ImageBrush ImageSource="..." Stretch="Fill"/> <!-- What should I write here? -->
            </Ellipse.Fill>
          </Ellipse>
        </Grid>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

This is how I create the buttons in XAML:

<Button Style="{StaticResource ButtonStyle}"/> //How do I specify a unique image?
<Button Style="{StaticResource ButtonStyle}"/>

I can also create these buttons from code behind if it is possible to do it there.

How do I use the same style but with different images?

Quality Catalyst
  • 6,531
  • 8
  • 38
  • 62
FewWords
  • 595
  • 1
  • 5
  • 22
  • see an example of parametrized template here: https://stackoverflow.com/questions/9232502/template-binding-with-attached-properties – ASh Aug 25 '17 at 08:34
  • If it's ok to specify the whole `ImageBrush` per button and not just the `ImageSource` path, you could use the `Button.Background` property with `TemplateBinding` – grek40 Aug 25 '17 at 08:50

2 Answers2

1

There are several ways that this could be achieved.

The most straight forward is to set the Background for each button to a ImageBrush :

<Button Width="120" Height="30" Style="{StaticResource ButtonStyle}">
    <Button.Background>
        <ImageBrush ImageSource="yourimage.jpg" Stretch="Fill" />
    </Button.Background>
</Button>

And then update the Style to use a TemplateBinding :

<Style TargetType="Button" x:Key="ButtonStyle">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="Button">
        <Grid>
          <Ellipse Fill="SlateGray"/>
          <Ellipse Margin="2" Fill={TemplateBinding Background} />
        </Grid>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

An alternative could be to create a custom button (ImageButton for instance) with a DependencyProperty that would be your image.

Tom C.
  • 593
  • 4
  • 12
0

You can bind Ellipse's Fill to the Background property of the Button. Then, in style set Background to default 'ImageBrush'. When you want to have button with different image, set 'Background' of that button to different image. You can even use different kind of Brush for that exceptional button, not only image.

Shadowed
  • 956
  • 7
  • 19