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();
}
1
  • 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;? Commented Nov 13, 2019 at 10:32

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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, you can declare Panel in xaml, e.g <Window><StackPanel Name="Root"/></Window>, and then add to it: Root.Children.Add(grd);. Or you can add to ContentControl anywhere in complex layout: <ContentControl Name="SomeControl"/>, SomeControl.Content = grd;. XAML can be almost fully translated into c#. Nested elements either set ContentProperty, or add to ContentCollection (Children, Items, etc)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.