【问题标题】:How to dynamically add RowDefinition or ColumnDefinition to a Grid with binding?如何通过绑定将 RowDefinition 或 ColumnDefinition 动态添加到 Grid?
【发布时间】:2012-01-25 09:45:49
【问题描述】:

我正在尝试创建一个具有可变行数和列数的表。我正在使用ItemsControl 执行此操作,Grid 作为其ItemsPanel。我知道我可以通过ItemContainerStyle 设置每个项目的Grid.RowGrid.Column。但是当我无法通过名称访问 Grid 时,我不知道如何更改行数和列数及其大小


问题:

如何在运行时在没有任何代码隐藏的情况下使用绑定修改RowDefinitionsColumnDefinitionsColumnDefinitions


这是 XAML 代码:

<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>

我尝试在后面的代码中添加一些RowDefinition,但我找不到通过名称(或任何其他方式)访问myGrid 的方法,因为它位于ItemsPanelTemplate 中。

我想知道是否有任何方法可以在运行时以编程方式添加或修改RowDefinitions

【问题讨论】:

    标签: wpf templates grid itemscontrol


    【解决方案1】:

    您可以将attached properties 用于Grid,在设置或更改这些属性时修改RowDefinitionsColumnDefinitions

    它允许你像这样写你的Grid

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

    然后只需从您的ViewModel 中公开一个属性,它会返回Cells 集合中的最大行号。

    您可以找到这些属性的详细实现on my blog

    【讨论】:

    • 非常感谢。我松了一口气:)顺便说一句,最后两种方法有一个小错误。我将它们更改为:GetStarColumns(grid).Split(',');
    • @Bizz 谢谢 :) 我第一次将代码复制到 wordpress 时,它去掉了所有特殊字符,我一定是错误地用双引号替换了单引号。额外的.ToString() 在那里,因为在我需要多个星形列并决定将其更新为字符串之前,星形列/行曾经是一个整数
    • 如何在 xaml 中定义本地?
    • @arund 通常类似于 &lt;Window&gt; 标签中的 xmlns:local="clr-namespace:MyProjectNamespace"。它告诉 WPF 使用术语“本地”作为指向 XML 命名空间 MyProjectNamespace 的快捷方式
    • 感谢更新@Rachel ..我使用 UniformGrid 而不是 Grid 和绑定行。 [链接]stackoverflow.com/questions/43627127/…
    【解决方案2】:

    如果您可以从代码隐藏访问网格,则可以这样做:

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

    【讨论】:

    • 这无济于事。我无法在代码中按名称访问myGrid
    • 当它是 ItemsControl 的 ItemPanelTemplate 时,您无法访问 whatever it。 @WtFudgE 您可能正在做其他事情。
    猜你喜欢
    • 1970-01-01
    • 2018-07-11
    • 2011-01-25
    • 2018-08-01
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 2018-07-21
    • 2011-11-10
    相关资源
    最近更新 更多