Benjamin Chambers
Benjamin Chambers

Reputation: 567

Flush grid layout of buttons in .Net for Windows Store App

I have a grid of objects that I am generating programmatically.

For testing purposes, each cell in the grid is a Border object whose child is an Image object. Each cell is placed flush against it's neighbor and displays perfectly.

When I replace each Image object with a Button object (each cell is still a Border object, just with a Button for its child rather than an Image), a noticeable gap appears between cells.

I have tried setting margin, padding, et al to 0.

What is unique about Buttons that makes them behave this way, and how can I overcome it?

Upvotes: 0

Views: 179

Answers (2)

Damir Arh
Damir Arh

Reputation: 17855

Margin is defined in the control template. you can change it by following these steps:

Right click on a button in the designer and select Edit Template > Edit a Copy... from the context menu.

Context menu

In the dialog select the name for the new style and choose where you want to put it.

Create style dialog

Now find the following block of XAML in the style and set Margin to 0.

<Border x:Name="Border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Margin="3">
    <ContentPresenter x:Name="ContentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" ContentTransitions="{TemplateBinding ContentTransitions}" Content="{TemplateBinding Content}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Border>

Assign the new style to all your buttons by either removing x:Key from the style declaration:

<Style TargetType="Button">
    <!-- style definition -->
</Style>

Or by setting the style to selected buttons:

<Button Style="{StaticResource MyButtonStyle}"/>

Either way, you'll have your buttons next to each other without any gap between them.

Upvotes: 1

sircodesalot
sircodesalot

Reputation: 11439

So I'm not strictly speaking familiar with how windows store apps work, but I don't imagine it's too far from general WPF / Silverlight. I get the same frustration from label controls with unnecessary padding when placed side by side. What you can do is just use negative-margin and that will correct it. I think it's totally not clean that you have to do that, but it does work.

Upvotes: 0

Related Questions