How to dynamically add RowDefinition or ColumnDefinition to a Grid with binding?

自古美人都是妖i 提交于 2019-12-17 02:23:16

问题


I'm trying to create a table with a variable number of rows and columns. I'm doing this with an ItemsControl which has a Grid as its ItemsPanel. And I know I can set Grid.Row and Grid.Column of each item through its ItemContainerStyle. But I don't know how to change the number of rows and columns and their sizes when I can't access the Grid by its name.


Question:

How can you modify RowDefinitions or ColumnDefinitions of a Grid in run-time without any code-behind using Binding?


This is the XAML code:

<ItemsControl Name="myItemsControl" ItemsSource="{Binding Cells}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Grid Name="myGrid">

                <Grid.RowDefinitions>
                    <!-- unknown number of rows are added here in run-time -->
                </Grid.RowDefinitions>

                <Grid.ColumnDefinitions>
                    <!-- known number of columns are added here in run-time -->
                </Grid.ColumnDefinitions>

            </Grid>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemContainerStyle>
        <Style.../>
    </ItemsControl.ItemContainerStyle>
</ItemsControl>

I tried to add some RowDefinition in code behind but I couldn't find a way to gain access to myGrid by its name (or any other way) since it is inside an ItemsPanelTemplate.

I'm wondering if is there any way to programmatically add or modify RowDefinitions in run-time?


回答1:


You can use attached properties for a Grid that modify the RowDefinitions and ColumnDefinitions when those properties are set or changed.

It will allow you to write your Grid like this:

<Grid local:GridHelpers.RowCount="{Binding MaxGridRow}"
      local:GridHelpers.ColumnCount="3" />

Then just expose a property from your ViewModel which returns the largest row number in the Cells collection.

You can find a detailed implementation of those properties on my blog.




回答2:


If you had access to the grid from code-behind you could do this:

var rowDefinition = new RowDefinition();
rowDefinition.Height = GridLength.Auto;
grid.RowDefinitions.Add(rowDefinition);


来源:https://stackoverflow.com/questions/9000549/how-to-dynamically-add-rowdefinition-or-columndefinition-to-a-grid-with-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!