DockPanel—最守规矩布局控件
DockPanel—最守规矩布局控件
这样子的一个DockPanel:
<DockPanel LastChildFill="True"> <TextBlock Text="1.Dock.Top" DockPanel.Dock="Top" Background="Bisque" Margin="0" Height="50" VerticalAlignment="Top"/> <TextBlock Text="2.Dock.Bottom" DockPanel.Dock="Bottom" Background="GreenYellow" Margin="0" Height="20" VerticalAlignment="Bottom"/> <TextBlock Text="3.Dock.Left" DockPanel.Dock="Left" Background="Tan" Width="100" /> <Grid DockPanel.Dock="Right" x:Name="gridRight" Width="200"> <TextBlock Text="4.Dock.Right" Background="Honeydew" HorizontalAlignment="Stretch"/> </Grid> <TextBlock Text="last" Background="Aquamarine" /> </DockPanel>
每个元素【守】 这一个边,很乖,中间的那个家伙可以趁父元素LastChildFill="True"的福分,独占剩余的区域。
守规矩因为两点:
- 元素只停靠某一个边,最后一个元素填充空白区域
- 严格遵从先来后到原则,尤其是【争议区域】
利用第一点,将边缘的空间缩进,让中间区域占用大量空间。
<Grid DockPanel.Dock="Right" x:Name="gridRight" Width="200"> <TextBlock Text="4.Dock.Right" Background="Honeydew" HorizontalAlignment="Stretch"/> <ToggleButton Content="->" Height="23" HorizontalAlignment="Left" Margin="0,50,0,0" Name="btnRight" VerticalAlignment="Top" Width="23" > <ToggleButton.Triggers> <EventTrigger RoutedEvent="ToggleButton.Checked"> <StopStoryboard BeginStoryboardName="collapsed" /> <BeginStoryboard x:Name="expand" HandoffBehavior="SnapshotAndReplace"> <Storyboard > <DoubleAnimation Duration="00:00:0.10 " Storyboard.TargetName="gridRight" Storyboard.TargetProperty="Width" To="50" /> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Content" > <DiscreteObjectKeyFrame Value="->" KeyTime="00:00:0.10" /> </ObjectAnimationUsingKeyFrames> </Storyboard> </BeginStoryboard> </EventTrigger> <EventTrigger RoutedEvent="ToggleButton.Unchecked"> <StopStoryboard BeginStoryboardName="expand" /> <BeginStoryboard x:Name="collapsed" HandoffBehavior="SnapshotAndReplace"> <Storyboard > <DoubleAnimation Duration="00:00:0.10 " Storyboard.TargetName="gridRight" Storyboard.TargetProperty="Width" To="200" /> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Content" > <DiscreteObjectKeyFrame Value="<-" KeyTime="00:00:0.10" /> </ObjectAnimationUsingKeyFrames> </Storyboard> </BeginStoryboard> </EventTrigger> </ToggleButton.Triggers> </ToggleButton> </Grid>
利用第二点,可以根据需要改变布局。
例如,左侧和下侧 有一个交叉的区域,如果想把这个区域划归左侧,那就把左侧的元素放在 下侧元素的前面,如下:
<TextBlock Text="3.Dock.Left" DockPanel.Dock="Left" Background="Tan" Width="100" /> <TextBlock Text="2.Dock.Bottom" DockPanel.Dock="Bottom" Background="GreenYellow" Margin="0" Height="20" VerticalAlignment="Bottom"/>