Why does my rectangle not appear in the grid?

I have this rectangle

    var rectangle = new Rectangle()
    {
        Width = double.NaN,
        Height = 32,
        HorizontalAlignment = HorizontalAlignment.Center,
        VerticalAlignment = VerticalAlignment.Top,
        Fill = Brushes.WhiteSmoke
    };

Which I add to the mainGrid of the window like this:

(mainWindow.Content as Grid).Children.Add(rectangle);

By doing this, the rectangle will not autofit to the grid width (it doesn’t even appear), however if I add an amount, say 300 to its width, it will appear in the grid at the position I indicated.

What am I doing wrong?

>Solution :

You can’t set both Width = double.NaN and HorizontalAlignment = HorizontalAlignment.Center.

Either assign a value to Width and let HorizontalAlignment to be Center,
Or assign set HorizontalAlignment = HorizontalAlignment.Stretch and let Width to be NaN.

Leave a Reply