Saurabh Goyal
Saurabh Goyal

Reputation: 647

margin of buttons in windows phone apps

I am dynamically generating a matrix of buttons(dynamic gridSize),everything is perfect except that I am unable to get them without spaces between them.I tried but could not understand how to use margin attribute.

460 is the width and height of gridPanel over which I am adding buttons

Here is the code from my app.cs file

private void generateButtons()
{
    for (int i = 0; i < gridSize; i++)
    {
        for (int j = 0; j < gridSize; j++)
        {
            buttons[i, j] = new Button();
            buttons[i, j].Content = "0";
            buttons[i, j].FontSize = 16;
            buttons[i, j].Height = 460/gridSize;
            double size = buttons[i, j].Height;
            buttons[i, j].Width = 460/gridSize;
            buttons[i, j].Foreground = new SolidColorBrush(Colors.Transparent);
            opened[i, j] = false;
            buttons[i, j].Margin = new Thickness(0 + (size * j), 0 + (size * i), 464 -                    (0 + (size * (j + 1))), 464 - (0 + (size * (i + 1))));
            buttons[i, j].Click += new RoutedEventHandler(cell_Click);
            this.gridPanel.Children.Add(buttons[i, j]);
        }
    }
}

Upvotes: 1

Views: 662

Answers (1)

lisp
lisp

Reputation: 4198

Most 'input controls' (buttons, textboxes etc) on Windows Phone have default spacings equal to 6.0 or 12.0. The simple workaround is to adjust margins of button by -12.

Sugestion unrelated to the question - when you want to populate a Grid uniformally with buttons, it would be perhaps easier, to generate a desired number of rows and columns and put every button in the different cell (with button.margin always equal to -12). All sizing calculations would be done by the Grid. Like this (gridPanel is Grid).

// generate rows and columns
for (int i = 0; i < gridSize; i++)
{
    gridPanel.RowDefinitions.Add(new RowDefinition());
    gridPanel.ColumnDefinitions.Add(new ColumnDefinition());
}

for (int i = 0; i < gridSize; i++)
{
    for (int j = 0; j < gridSize; j++)
    {
        buttons[i, j] = new Button
            {
                Content = "0",
                FontSize = 16,
                Foreground = new SolidColorBrush(Colors.Transparent),
                // all buttons have the same margin, no calculation needed
                Margin = new Thickness(-12) 
            };
        // placing in a row and column via attached properties
        buttons[i, j].SetValue(Grid.RowProperty, i);
        buttons[i, j].SetValue(Grid.ColumnProperty, j);
        buttons[i, j].Click += new RoutedEventHandler(cell_Click);
        opened[i, j] = false;
        this.gridPanel.Children.Add(buttons[i, j]);
    }
}

Upvotes: 1

Related Questions