How to insert Dynamic Grid into the WPF XAML interface

Asked

Viewed 24 times

-1

I wrote a method that creates a Grid dynamically:

private void createMyGrid(int l, int c)
{
    //Create grid
    Grid DynamicGrid = new Grid();
    DynamicGrid.ShowGridLines = true;

    //Create lines
    for(int i=0; i<l;i++)
    {
        DynamicGrid.RowDefinitions.Add(new RowDefinition());
    }

    //create columns
    for (int j = 0; j < c; j++)
    {
        DynamicGrid.ColumnDefinitions.Add(new ColumnDefinition());
    }

    // Display grid into a Window
    this.Content = DynamicGrid;    

}

Mainwindow.xaml looks like this:

<Window x:Class="dinamicButtonBasics.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:dinamicButtonBasics"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Grid x:Name="mainGrid">
    <Grid x:Name="myGrid">

    </Grid>
</Grid>

Is it possible to make my "myGrid" become the one I created dynamically? Otherwise, how can I replace "myGrid" with the one created by the function?

1 answer

0

After all it was simple ...

public MainWindow()
{
    InitializeComponent();
    myGrid.Children.Clear();
    myGrid.Children.Add(createMyGrid(3,4));
}

... but the function was changed so:

private Grid createMyGrid(int l, int c)
{
    //Create grid
    Grid DynamicGrid = new Grid();
    DynamicGrid.ShowGridLines = true;

    //Create lines
    for(int i=0; i<l;i++)
    {
        DynamicGrid.RowDefinitions.Add(new RowDefinition());
    }

    //create columns
    for (int j = 0; j < c; j++)
    {
        DynamicGrid.ColumnDefinitions.Add(new ColumnDefinition());
    }

    //Add buttons ti the grid
    populateGrid(DynamicGrid);

    return DynamicGrid;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.