【问题标题】:Update button location automatically in grid wpf在网格 wpf 中自动更新按钮位置
【发布时间】:2011-05-05 11:57:07
【问题描述】:

我有 3*3 的网格,里面有 9 个按钮。这些按钮的可用性是在运行时确定的,因此按钮必须排列在可用空间中。

示例:

b1 b2 b3

b4 b5 b6

b7 b8 b9

如果 b5 按钮不可用,那么我必须这样做

b1 b2 b3

b4 b6 b7

b8 b9

目前在可见性更新处理程序中,我正在检查所有控件状态并更改 grid.row 和 grid.column。有没有更好的办法?

【问题讨论】:

  • 你考虑过WrapPanel而不是网格吗?
  • @Bala +1 这似乎正是包装面板的作用

标签: c# wpf grid


【解决方案1】:

按照 Bala R 的回答,您似乎正在尝试实现自己的 WrapPanel。

WrapPanel 内置了这样的功能,它会自动重新排列您的控件“从左到右然后从上到下”或“从上到下然后从左到右”。然后,您不再需要“观察”按钮的可见性,因为一旦一个按钮不可见(折叠),其他按钮就会立即取代后面的位置,然后再遵循上述模式。

这里有一个快速而肮脏的示例来说明,随意使用 WrapPanel 方向和折叠/隐藏按钮状态:

XAML:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="31*" />
        <RowDefinition Height="731*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="284*" />
        <ColumnDefinition Width="294*" />
    </Grid.ColumnDefinitions>
    <StackPanel Orientation="Horizontal"  VerticalAlignment="Top">
        <Button x:Name="hideBtn" Content="HIDE button #" Click="hideBtn_Click"></Button>
        <TextBox x:Name="buttonNumber" Width="50"></TextBox>
        <RadioButton x:Name="radioCollapsed" Content="Collapsed" IsChecked="True"></RadioButton>
        <RadioButton x:Name="radioHidden" Content="Hidden"></RadioButton>
    </StackPanel>

    <WrapPanel x:Name="wp" Orientation="Horizontal"  Grid.Row="1" VerticalAlignment="Top" HorizontalAlignment="Left" Height="74" Width="61">
        <Button x:Name="b_1" Content="B1"></Button>
        <Button x:Name="b_2" Content="B2"></Button>
        <Button x:Name="b_3" Content="B3"></Button>
        <Button x:Name="b_4" Content="B4"></Button>
        <Button x:Name="b_5" Content="B5"></Button>
        <Button x:Name="b_6" Content="B6"></Button>
        <Button x:Name="b_7" Content="B7"></Button>
        <Button x:Name="b_8" Content="B8"></Button>
        <Button x:Name="b_9" Content="B9"></Button>
    </WrapPanel>
</Grid>

后面的代码:

    private void hideBtn_Click(object sender, RoutedEventArgs e)
    {
        foreach (var child in wp.Children)
        {
            var btn = (Button)child;
            btn.Visibility = Visibility.Visible;
        }
        foreach (var child in wp.Children)
        {
            var btn = (Button)child;

            if (btn.Name.Contains(buttonNumber.Text))
            {
                if (radioCollapsed.IsChecked.Value)
                    btn.Visibility = Visibility.Collapsed;
                else
                    btn.Visibility = Visibility.Hidden;
            }
        }
    }

【讨论】:

    【解决方案2】:

    尝试使用 UniformGrid 并将 Columns 和 Rows 设置为 3。它将按照您刚才描述的方式自动填充网格。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-29
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多