fede186
fede186

Reputation: 89

How to add a Controls.Grid in a Canvas

I would like add a Grid in a Canvas and put inside a Rectangle.

Here my code

        Grid gridForModules = new Grid();       
        Canvas.SetLeft(gridForModules, 600);
        Canvas.SetTop(gridForModules, 80);
        AddRowsOfGrid(gridForModules, 5);
        AddColumnsOfGrid(gridForModules, 8);
        gridForModules.ShowGridLines = true;
        m_grid.RegisterName("ModulesGRID", gridForModules);
        m_canvas.Children.Add(gridForModules);


        Rectangle rect = new Rectangle();
        Grid.SetColumn(rect, 2);
        Grid.SetRow(rect, 2);
        Grid.SetRowSpan(rect, 2);
        Grid.SetColumnSpan(rect, 2);
        rect.Fill = new SolidColorBrush(Colors.Coral);
        rect.Name = "ModuloEsempio";
        gridForModules.Children.Add(rect);
        m_grid.RegisterName(rect.Name, rect);

Thanks

Upvotes: 0

Views: 51

Answers (1)

haindl
haindl

Reputation: 3221

You specify that the columns/rows of the Grid should be equally wide/high by setting new GridLength(1.0, GridUnitType.Star) on both. So if you have 5 rows then the height of each row should be the height of the Grid divided by 5.

The problem in your code is that the Grid doesn't have a height or width because the Canvas is just a drawing board that doesn't size its contents.

To solve your problem you either have to set the size on the Grid using

gridForModules.Width = 300;
gridForModules.Height = 200;

or you have to set it in the Column/RowDefinitions

col.Width = new GridLength(30);
row.Height = new GridLength(30);

After that you should see your Grid and your Rectangle (if you look a bit far to the right).

Upvotes: 1

Related Questions