lundi 11 mai 2015

How to place buttons in a canvas dynamically so that it won't overlap each other?

I am writing an application in C#, WPF, Windows Phone 8.1 apps and I have one canvas in a 480x480 rectangular grid, and I want to put some buttons onto the canvas based on certain logic, there will be minimum 5 buttons and maximum 12-15 buttons, now based upon certain conditions I want to put buttons in the canvas so that it does not overlap with each other.

I started with Grid idea initially with number of rows and columns set and every row/column will have only one buttons, Suppose I have 6 buttons I will call this method CreateButtonsControls(3,3); but the way it placed the Buttons inside the grid it looks very monotonous to me.

private void CreateButtonsControls(int rows, int columns)
    {
        // Create a Grid
        Grid rootGrid = new Grid();

        // It will create columns
        createColumns(rootGrid, columns);

        // It will create rows
        createRow(rootGrid, rows);

        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < columns; j++)
            {
                Button button = new Button();
                button.HorizontalAlignment = HorizontalAlignment.Right;
                button.VerticalAlignment = VerticalAlignment.Top;
                button.Margin = new Thickness(3);
                button.Width = 50;
                button.Height = 50;
                button.Content = "12";
                Grid.SetRow(button, i);
                Grid.SetColumn(button, j);
                rootGrid.Children.Add(button);
            }
        }
        // This will add the root grid to UI
        grdButton.Children.Add(rootGrid);

    }

and I thought to implement it in a canvas. I want that all the buttons will be placed inside the canvas scatter way. But I don't know how can I achieve this.

There is one property
Canvas.SetLeft(UIControl, positionX ) Canvas.SetTop(UIControl, positionY )

But How do I decide this positionX and positionY at runtime so that it doesnot overlap eachother, any idea or suggestions?

Thanks

Aucun commentaire:

Enregistrer un commentaire