How can I create and display WPF content from C# code?

935 Views Asked by At

I'm working on a WPF App, and I would like to create the entire window from c# code, instead of from XML.

I tried the following code, but nothing happens, the grid is not displayed. Did I miss something? Is it possible to do it this way or is there any other solution?

public MainWindow()
{
    Grid grd = new Grid();
    grd.Margin = new System.Windows.Thickness(10, 10, 10, 0);
    grd.Background = new SolidColorBrush(Colors.White);
    grd.Height = 104;
    grd.VerticalAlignment = System.Windows.VerticalAlignment.Top;
    grd.ColumnDefinitions.Add(new ColumnDefinition());
    grd.ColumnDefinitions.Add(new ColumnDefinition());
    grd.ColumnDefinitions.Add(new ColumnDefinition());

    RowDefinition row = new RowDefinition();
    row.Height = new System.Windows.GridLength(45);
    grd.RowDefinitions.Add(row);

    row = new RowDefinition();
    row.Height = new System.Windows.GridLength(45);
    grd.RowDefinitions.Add(row);

    row = new RowDefinition();
    row.Height = new System.Windows.GridLength(45);
    grd.RowDefinitions.Add(row);
    InitializeComponent();
}
1

There are 1 best solutions below

2
ASh On BEST ANSWER

Grid grd was created, but not added to Window.

InitializeComponent();
this.Content = grd;

it will replace all content which was declared in XAML (if any).

However, Grid is a Panel and doesn' have visual representation itself, so window with Grid without child element will still look empty. Try grd.ShowGridLines = true; to see rows and columns

Grid documentation shows a large example actually, with equivalent c# code and xaml markup