Programer
Programer

Reputation: 1035

Global Button's Dynamic Style with different image for each button

I am using Buttons in Wpf C# application. I have declared a style for those buttons:

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

I want this style to be applied to all buttons in my Window, but the image to be different.

I could have created many Styles by duplicating the code and setting each button a style of its own, while changing only the image, but I dont want this redundency.

I set the button style like this:

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

As I mentioned, I have many buttons like this, and I want them all to have the same style but to change the image source in this style for each button.

Is there a way to do it without creating the same style with a different name for each button?

Upvotes: 3

Views: 742

Answers (1)

Scott Boettger
Scott Boettger

Reputation: 3667

Why don't you just place the image inside the button instead of in the style.

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

The Style would then look like this:

<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: If you have text and image use a stack panel:

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

Using the stack panel will allow you to either use vertical or horizontal orientation for your button layout. The text and image can then be positioned using margins inside the button.

Upvotes: 3

Related Questions