在网格中添加动态图块和列 [英] Adding dynamic tiles and columns in a grid

查看:60
本文介绍了在网格中添加动态图块和列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个4 * 4行和列的网格.我需要一个xaml.cs页面的代码,以我为例,我取一个变量,其中x = 2,3,4,5,....因此,在运行时,当x = 2时,将显示两个图块 如果x = 3,则将在网格中显示三个图块,如果没有,则显示三个图块.的磁贴数大于16,然后会在其中添加新列.

I have a grid of 4*4 rows and columns. I need a code for xaml.cs page lets for take example I take a variable where x=2,3,4,5,.... So at runtime when x=2 two tiles will be displayed in the grid, if x=3 three tiles will be displayed in the grid and accordingly if no. of tiles will be greater than 16 then a new column will get added into it.

有人可以为此写一小段代码吗?只是逻辑部分.

谢谢!

推荐答案

>> 任何人都可以为此编写一小段代码.只是逻辑部分.

请参考以下示例代码.它应该给你这个主意.

Please refer to the following sample code. It should give you the idea.

        <Grid x:Name="grid">
            <Grid.ColumnDefinitions>
                <ColumnDefinition/>
                <ColumnDefinition/>
                <ColumnDefinition/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition/>
                <RowDefinition/>
                <RowDefinition/>
                <RowDefinition/>
            </Grid.RowDefinitions>
        </Grid>


const int x = 16;
            int lastColumnIndex = grid.ColumnDefinitions.Count - 1;
            int lastRowIndex = grid.RowDefinitions.Count - 1;
            int row = 0;
            int column = 0;
            int startColumn = 0;
            for(int i = 0; i < x; ++i)
            {
                if (column > lastColumnIndex)
                {
                    row++;
                    column = startColumn;
                }
                if (row > lastRowIndex)
                {
                    grid.ColumnDefinitions.Add(new ColumnDefinition());
                    lastColumnIndex++;
                    column = lastColumnIndex;
                    startColumn = lastColumnIndex;
                    row = 0;
                }

                Button tile = new Button() { Width = 50, Height = 50, Content = i.ToString(), Margin = new Thickness(2) };
                Grid.SetRow(tile, row);
                Grid.SetColumn(tile, column);
                grid.Children.Add(tile);

                column++;
            }


希望有帮助.

请记住,通过将有用的帖子标记为答案来关闭话题,然后在遇到新问题时开始新话题.请不要在同一线程中问几个问题.

Please remember to close your threads by marking helpful posts as answer and then start a new thread if you have a new question. Please don't ask several questions in the same thread.


这篇关于在网格中添加动态图块和列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆