Alan2
Alan2

Reputation: 24572

How can I create a Grid.ColumnDefinition in C#?

Here is the code I have:

var column1 = new ColumnDefinition()
{
    Width = new GridLength(1, GridUnitType.Star)
};
var column2 = new ColumnDefinition()
{
    Width = new GridLength(30, GridUnitType.Absolute)
};

this.ColumnDefinitions.Add(column1);
this.ColumnDefinitions.Add(column2);

I tried to put the first definition in one line like this but it gives me an error:

this.ColumnDefinitions.Add(new ColumnDefinition(Width = new GridLength(1, GridUnitType.Star))

It is saying that ColumnDefinition does not take a constructor that takes one argument.

Does anyone have any idea no how to fix this problem?

Upvotes: 1

Views: 515

Answers (3)

Mihail Duchev
Mihail Duchev

Reputation: 4821

You are mixing the terminology of constructor & initialiser. The ColumnDefinition has only one constructor - the default one. On the other case, you can initialise the Width property from the ColumnDefinition's initialiser, like you have done in the first lines of code. Basically, the initialiser invokes the default ctor and then it populates its properties with the values that you have provided.

What you can do in this case is:

this.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });

You can read more about initialisers in C# here.

Upvotes: 2

Brandon Minnick
Brandon Minnick

Reputation: 15340

I highly recommend using C# Markup Extensions, introduced in Xamarin.Forms v4.6.

Here's an example from my app, GitTrends: https://github.com/brminnick/GitTrends/blob/4045027a32b9eeadc3a10c5ed94df9199738cb2a/GitTrends/Views/ReferringSites/ReferringSitesDataTemplate.cs.

using Xamarin.Forms;
using Xamarin.Forms.Markup;
using static Xamarin.Forms.Markup.GridRowsColumns;

class CardView : Grid
{
    public CardView()
    {
        RowSpacing = 0;
        RowDefinitions = Rows.Define(
            (Row.TopPadding, AbsoluteGridLength(TopPadding)),
            (Row.Card, Star),
            (Row.BottomPadding, AbsoluteGridLength(BottomPadding)));

        ColumnDefinitions = Columns.Define(
            (Column.LeftPadding, AbsoluteGridLength(16)),
            (Column.Card, Star),
            (Column.RightPadding, AbsoluteGridLength(16)));

        Children.Add(new CardViewFrame().Row(Row.Card).Column(Column.Card));
    }

    enum Row { TopPadding, Card, BottomPadding }
    enum Column { LeftPadding, Card, RightPadding }
}

https://github.com/brminnick/GitTrends/blob/4045027a32b9eeadc3a10c5ed94df9199738cb2a/GitTrends/Views/ReferringSites/ReferringSitesDataTemplate.cs

Upvotes: 1

Jason
Jason

Reputation: 89102

the docs clearly show that ColumnDefinition only has an empty constructor

var col = new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) };
this.ColumnDefinitions.Add(col);

Upvotes: 3

Related Questions