在这种情况下使用Grid
可能非常有用,因为您的控件具有相当明确的位置和相对大小。
要使用它,请为您的网格创建行和列,并添加控件以指定它应该填充的单元格。
例如,
<Grid Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="4*" />
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition Width="3*" />
</Grid.ColumnDefinitions>
<ListBox x:Name="itemList" Grid.Row="0" Grid.Column="0" Background="Green" />
<UserControl x:Name="infoPanel" Grid.Row="1" Grid.RowSpan="2" Grid.Column="0" Background="Yellow" />
<UserControl x:Name="mediaElement" Grid.Row="0" Grid.RowSpan="2" Grid.Column="1" Background="Blue" />
<StackPanel Grid.Row="2" Grid.Column="1" Background="Red"
Orientation="Horizontal" HorizontalAlignment="Center">
<StackPanel.Resources>
<Style TargetType="Button">
<Setter Property="Margin" Value="5" />
<Setter Property="Background" Value="Aqua" />
</Style>
</StackPanel.Resources>
<Button>button1</Button>
<Button>button2</Button>
<Button>button3</Button>
</StackPanel>
</Grid>
给你一个布局,看起来像这样:
当然也有很多方法可以实现这一布局,所以要学会什么是提供给您,以及如何你可以使用它们来实现你想要的。
要添加另一行来放置您的项目,您需要做几件事。
- 将新的
RowDefinition
添加到RowDefinitions
,指定高度(如有必要)。
- 将所有位于新行下方的控件移到下一个(将
Grid.Row
加1)。
- 跨越多行且正在被此新行剪切的任何控件也应该增加1(通过将其加1到
Grid.RowSpan
)。
注意设计师,它可以真正帮助你在这里。
所以在这个例子中,作出这些调整,你可以这样做:
<Grid Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="4*" />
<RowDefinition Height="25" />
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition Width="3*" />
</Grid.ColumnDefinitions>
<ListBox x:Name="itemList" Grid.Row="0" Grid.Column="0" Background="Green" />
<StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Center" Background="Orange">
<StackPanel.Resources>
<Style TargetType="Button">
<Setter Property="Margin" Value="5,0,5,0" />
<Setter Property="Background" Value="Turquoise" />
</Style>
</StackPanel.Resources>
<Button>button4</Button>
<Button>button5</Button>
</StackPanel>
<UserControl x:Name="infoPanel" Grid.Row="2" Grid.RowSpan="2" Grid.Column="0" Background="Yellow" />
<UserControl x:Name="mediaElement" Grid.Row="0" Grid.RowSpan="3" Grid.Column="1" Background="Blue" />
<StackPanel Grid.Row="3" Grid.Column="1" Background="Red"
Orientation="Horizontal" HorizontalAlignment="Center">
<StackPanel.Resources>
<Style TargetType="Button">
<Setter Property="Margin" Value="5" />
<Setter Property="Background" Value="Aqua" />
</Style>
</StackPanel.Resources>
<Button>button1</Button>
<Button>button2</Button>
<Button>button3</Button>
</StackPanel>
</Grid>
这将产生以下结果:
我怎么会适合另一在黄色和绿色面板之间的StackPanel?我已经尝试将黄色面板移动到Grid.Row =“2”,但最终会失去太多高度。新的StackPanel只需要25px的高度,因为它只包含两个小按钮。 – rafale
您必须在网格中添加另一行,并将该行下方的所有控件移到下一行。请注意,这使用相对大小。您可以通过'*'调整数字来调整大小。如果您没有明确添加高度/宽度,则将其视为1 *'。我将展开我的回答,以展示我的意思。 –