【问题标题】:how to get grid children by its row and column in wpf?如何通过 wpf 中的行和列获取网格子项?
【发布时间】:2025-12-15 13:15:02
【问题描述】:
<Grid x:Name="LayoutRoot" HorizontalAlignment="Center" VerticalAlignment="Center" >
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>
    <Button Width="150" Height="50" x:Name="Btn1" Content="Button1" Grid.Row="0" Grid.Column="0"/>
    <Button Width="150" Height="50" x:Name="Btn2" Content="Button2" Grid.Row="0" Grid.Column="1"/>
    <Button Width="150" Height="50" x:Name="Btn3" Content="Button3" Grid.Row="2" Grid.Column="0"/>
    <Button Width="150" Height="50" x:Name="Btn4" Content="Button4" Grid.Row="2" Grid.Column="1"/>
</Grid>

wpf 中的 C# 代码

Visual childVisual = (Visual)VisualTreeHelper.GetChild(LayoutRoot,0);

使用上面的代码,我可以获得网格的第一个子项(LayoutRoot)。但我想通过它的行或列来获取网格子项。我该怎么办。

提前致谢。

【问题讨论】:

  • 您通常永远不应该使用VisualTreeHelper

标签: c# wpf xaml grid


【解决方案1】:

根据Grid.GetRowGetColumn 为每个孩子返回的内容过滤Grid.Children

例如

var itemsInFirstRow = LayoutRoot.Children
                          .Cast<UIElement>()
                          .Where(i => Grid.GetRow(i) == 0);

【讨论】:

  • @ChandruA:看到这个例子了吗?无论如何,如果您需要查找 UI 元素,您可能做错了什么,您的代码可能需要更多 data bindingcommands
  • var itemsInFirstRow = LayoutRoot.Children.Where(i => Grid.GetRow(i) == 0);它显示错误。
  • 你必须写LayoutRoot.Children.Cast&lt;UIElement&gt;().Where(i =&gt; Grid.GetRow(i) == 0)
  • 我同意 H.B.这不是一个好方法。如果稍后将行或列添加到网格中或从网格中删除,会发生什么情况。您或其他开发人员是否记得或知道要更改该硬编码数字?
最近更新 更多