简体   繁体   中英

How to Add Column infront of another column through Code Behind?

While I am in XAML, say I have 2 Column Definitions:

<Grid.ColumnDefinition>
    <ColumnDefinition>
    <ColumnDefinition>
</Grid.ColumnDefinition>

I would like to add an Extra Column at 0th Position in Code behind. But When I add column it automatically embed as the 2nd Positon Column.

You need to get hold of your grid and than insert into the columndefinitions rather than 'Add'.

 Grid layoutRoot = new Grid();
 layoutRoot.ColumnDefinitions.Insert(0, new ColumnDefinition() { Width = new GridLength(0, GridUnitType.Star) });

I think you are coding like following which I think is correct.

Grid1.ColumnDefinitions.Insert(0, new ColumnDefinition());

There are one more thing you need to do is to plus one to the children in the grid like this, or else, the old items will be put in the first column; so the effect is like what you saw just now.

foreach (UIElement item in Grid1.Children)
{
    var columnIndex = Grid.GetColumn(item);
    Grid.SetColumn(item, columnIndex + 1);
}

Here is the simple way to achieve this.

Maingrid.ColumnDefinitions.Insert(0, new ColumnDefinition());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM