user720694
user720694

Reputation: 2075

Convert image to a button WPF

I understand that i can overlay an image on a button, but is it possible that a button can take the exact size of an image? In other words, i want to get rid of the rectangular shaped button and adapt it to the size and shape of the image.

Upvotes: 3

Views: 2266

Answers (3)

RonakThakkar
RonakThakkar

Reputation: 903

In above code, you are hardcoding the image path. if you want to reuse the template try this code. There are 2 ways.

if you are embedding an image in project then below.

<Button Tag="Images\Grapes.png" Background="Black" Foreground="white" Focusable="False" Width="100" Height="30">
        <Button.Template>
            <ControlTemplate TargetType="Button">                    
                <Image Source="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=Tag}" />
            </ControlTemplate>
        </Button.Template>
    </Button>

if you are adding image as content in project the below code using absolute path.

<Button Tag="pack://siteoforigin:,,,/Apple.png">
        <Button.Template>
            <ControlTemplate>
                <Border HorizontalAlignment="Center" VerticalAlignment="Center">
                    <Image Source="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=Tag}" Stretch="None" />                        
                </Border>
            </ControlTemplate>
        </Button.Template>
    </Button>

Upvotes: 0

Nitin Purohit
Nitin Purohit

Reputation: 18578

You can set the Template of button like below:

    <Button >
        <Image Source="pan-left.png"/>
        <Button.Template>
            <ControlTemplate TargetType="Button">
                <ContentPresenter Content="{TemplateBinding Content}"/>
            </ControlTemplate>
        </Button.Template>
    </Button>

TemplateBinding is used to set the Content property in order to set the Content inside the ControlTemplate, as you can move this ControlTemplate to the Resources and can use it for multiple button and you can set the content on button itself

Upvotes: 6

user1522991
user1522991

Reputation:

Check this Question.

You can re-template the button.

<Button x:Name="btn16x16">
    <Button.Template>
        <ControlTemplate>
            <Border HorizontalAlignment="Center" VerticalAlignment="Center" >
                <Image Source="pack://siteoforigin:,,,/Resources/SixteenBySixteen.png" 
                       Width="16" 
                       Height="16"/>
            </Border>
        </ControlTemplate>
    </Button.Template>
</Button>

Upvotes: 1

Related Questions