我有3 * 3的网格,并有9个按钮。这些按钮可用性是在运行时确定的,因此按钮必须安排在可用空间内。在网格中自动更新按钮的位置wpf
例如:
B1,B2,B3
B4 B5 B6
B7 B8 B9
如果B5按钮不可用,那么我必须做这样的
B1,B2, b3
b4 b6 b7
b8 b9
当前在可见性更新处理程序中,我检查所有控件状态并更改grid.row和grid.column。有没有更好的方法来做到这一点?
我有3 * 3的网格,并有9个按钮。这些按钮可用性是在运行时确定的,因此按钮必须安排在可用空间内。在网格中自动更新按钮的位置wpf
例如:
B1,B2,B3
B4 B5 B6
B7 B8 B9
如果B5按钮不可用,那么我必须做这样的
B1,B2, b3
b4 b6 b7
b8 b9
当前在可见性更新处理程序中,我检查所有控件状态并更改grid.row和grid.column。有没有更好的方法来做到这一点?
继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;
}
}
}
尝试使用UniformGrid并将列和行设置为3.它将自动按照刚描述的方式填充网格。
你考虑过[WrapPanel](http://msdn.microsoft.com/en-us/library/system.windows.controls.wrappanel.aspx)而不是网格吗? – 2011-05-05 12:22:42
@Bala +1这似乎正是一个包装面板 – Bruno 2011-05-05 12:26:56