Home > Software engineering >  What is the easiest way to put an icon beside a centered button?
What is the easiest way to put an icon beside a centered button?

Time:04-29

I have a button and an icon :

<Button Content="Hello" Click="MyHandler"/>
<Image Source="icon.ico"/>

I'd like the button to be centered in its container and the icon to be right beside it, like so :

A button that is centered and an image next to it on the right.

Whatever the size of the screen, the button and its icon should stay at the same distance from each other.

I tried with a Grid and a StackPanel, but I can't get a proper result.

How could I achieve this?

CodePudding user response:

If you want the combination of Button and Image centered as one, you could use a StackPanel.

<StackPanel Orientation="Horizontal"
            HorizontalAlignment="Center"
            VerticalAlignment="Center">
    <Button Content="Hello"
            Click="MyHandler"/>
    <Image Source="icon.ico"/>
</StackPanel>

If only the Button should be centered and the Image put next to it, a Grid could be used.

<Grid VerticalAlignment="Center">
     <Grid.ColumnDefinitions>
         <ColumnDefinition Width="*"/>
         <ColumnDefinition Width="Auto"/>
         <ColumnDefinition Width="*"/>
     </Grid.ColumnDefinitions>
     <Button Grid.Column="1"
             Content="Hello"
             Click="MyHandler"/>
    <Image Grid.Column="2"
           HorizontalAlignment="Left"
           Source="icon.ico"/>
</Grid>
  • Related