Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Image Button formatting

Tags:

wpf

If I create a button with an image inside, it gets blown up to much larger size than the image.

If i try to constrain the size of image, and container button, the image gets cut off:

<Button Background="Transparent" Width="18" Height="18" Margin="0,0,0,0" Padding="0,0,0,0" BorderBrush="{x:Null}">     <Image Width="16" Height="16" /> </Button> 

Native image size is 16x16. Here the button is 18x18 with 0 padding, yet the image still gets cut-off on right/bottom.

how can i make the entire button be exactly the size of the image w/out any cut off?

like image 310
Sonic Soul Avatar asked Jun 08 '10 12:06

Sonic Soul


2 Answers

The beauty (and curse?) of WPF is the ability to re-template controls.

You can set the template of the button something like the following (this is free hand, so you will need to tweak it a bit for your tastes):

        <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> 
like image 187
Wonko the Sane Avatar answered Sep 28 '22 17:09

Wonko the Sane


You should remove any Width and Height settings and set the Button's HorizontalAlignment and VerticalAlignment both to Center (or Left/Right or Top/Bottom resp.). By default, these properties are set to Stretch which makes the button stretch to the available space. Since the image is the content of the button, it also gets stretched. Something like this should work:

Take this code example:

<Button Background="Transparent" BorderBrush="{x:Null}" HorizontalAlignment="Center" VerticalAlignment="Center">     <Image Source="thePathToYourImage" Stretch="None"/> <!-- EDIT: added Stretch="None" here! --> </Button> 

.


The following was just meant as an alternative with a different result which obviously (considering your comments) is not what you want.

If you want the button to stretch, but not the image, you could also set the Image's alignment properties to something other than Stretch. Or you could set its Stretch property to None. This would make the button as large as possible, but keep the image at its original size (16x16). This would work as follows:

<Button Background="Transparent" BorderBrush="{x:Null}">     <Image Source="thePathToYourImage" HorizontalAlignment="Center" VerticalAlignment="Center"/> </Button> <!-- OR: --> <Button Background="Transparent" BorderBrush="{x:Null}">     <Image Source="thePathToYourImage" Stretch="None"/> </Button> 

like image 22
gehho Avatar answered Sep 28 '22 17:09

gehho