0

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();
}
ASh
  • 34,632
  • 9
  • 60
  • 82
Axel
  • 165
  • 3
  • 14
  • 3
    You haven't added the grid to the window. I am not 100% sure as it's been a long time since I did this, but perhaps something like `this.Content = grd;`? – DavidG Nov 13 '19 at 10:32

1 Answers1

1

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

ASh
  • 34,632
  • 9
  • 60
  • 82
  • It worked, thanks. Is there a way to add something to this.Content instead of replacing it? Like this.Content += grd maybe? By the way, the background of my window is grey and the background of the grid is white, so i can see it even without child elements ;) – Axel Nov 13 '19 at 10:40
  • 1
    @Axel, you can declare Panel in xaml, e.g ``, and then add to it: `Root.Children.Add(grd);`. Or you can add to ContentControl anywhere in complex layout: ``, `SomeControl.Content = grd;`. XAML can be almost fully translated into c#. Nested elements either set ContentProperty, or add to ContentCollection (Children, Items, etc) – ASh Nov 13 '19 at 11:13