WrapPanel和DockPanel也是連個比較簡單的布局容器,這兩個空間將彌補StackPanel的某些不足,該開發人員更多可選擇的布局方式,這兩個作用如下:
WrapPanel控件:該控件根據Orientation屬性,在垂直疊放控件或者在行中放置控件方面,WrapPanel與StackPanel類似。除了疊放外,WrapPanel還未包含的控件提供了換行支持,因此,如果在WrapPanel
中放入超過其容器寬度的內容時,這些控件被換行顯示以形成換行效果,
DockPanel控件:DockPanel提供停靠支持,以便讓工具欄或用戶希望停靠在面板一側的其他控件容易定位。
使用WrapPanel控件布局
與Stackpanel控件類似,WrapPanel也有一個Orientation屬性,默認值Horizontal,控件將從左向右進行排列。如果容器的寬度不足以排放所有控件時,將會一個新行從左向右進行排列
。Orientation屬性的另外一個選擇是vertical,元素從上到下排列。
WrapPanel通常用在一些小范圍的布局場合,而不是整個窗口的總體布局,比如可以使用WrapPanel來保持控件以一種類似工具條的形式,下面看實例:
<WrapPanel Margin="3"> <Button Name="btn1" Content="按鈕1" VerticalAlignment="Top" /> <Button Name="btn2" MaxHeight="60" Content="按鈕2" /> <Button Name="btn3" VerticalAlignment="Center">居中按鈕</Button> </WrapPanel>
在代碼中,添加3個按鈕,並為這些按鈕分別設置了verticalAlignment屬性,已設置按鈕在控件中的對齊方式,也許讀者會覺得這與Stackpanel沒什么區別,但是如果調整主窗體大小,則
會看到當寬度不夠擺放在一行時,WrapPanel將換一個新的行進行按鈕的顯示。
使用DockPanel控件布局
Dockpanel容器面板用於拉伸空間以停靠在指定的窗口邊緣。比如,在Windows Forms中的工具欄,通常停靠在Windows窗體的頂端 放置在Dockpanel中的控件將被拉伸以適應容器的邊緣。
比如,將一個Button控件Dock在容器的頂部,則控件的寬度被拉伸以適應容器的寬度,而高度則保持適應內容的大小。
DockPanel 控件提供了附加屬性Dock。這是一個Dock枚舉類型,可選的值如下,
Left:位於DockPanel左側的子元素。
Top:位於DockPanel的頂部的子元素。
Right:位於DockPanel右側的子元素。
Bottom:位於DockPanel底部的子元素。
容器中的子元素可以使用Dock屬性來設置要停靠的容器邊緣,下面新建一個DockpanelDemo的示例,而高度保持適應內容的大小
<DockPanel> <Button x:Name="button" Content="Button" DockPanel.Dock="Top" /> <Button x:Name="button1" Content="Button" DockPanel.Dock="Bottom" /> <Button x:Name="button2" Content="button" DockPanel.Dock="Left"/> <Button Name="btn1" Content="button2" DockPanel.Dock="Right"/> <Button x:Name="button3" Content="Button" /> </DockPanel>
如下圖:
在這個XAML文檔中,DockPanel上、下、左、右分別放置了一個Button 通過使用DockPanel控件的附加屬性,將Button控件分別Dock到容器的4個邊緣
需要注意的是最后一個Button,該Button沒有設置任何屬性,但是會自動沾滿DockPanel控件的剩余部分空間,這是因為為DockPanel控件指定了LastChildFill屬性。
注意:如果將LastChildFill屬性設置為true,這是默認設置,則無論對DockPanel的最后一個子元素設置的其他任何停靠值是什么,該元素都將始終填滿剩余的控件。要將子元素停靠在另一個方向,必須將LastChildFill屬性設置為false,還必須對最后一個子元素設置I顯示停靠的方向。
<DockPanel LastChildFill="False"> <Button x:Name="button" Content="Button" DockPanel.Dock="Top" /> <Button x:Name="button1" Content="Button" DockPanel.Dock="Bottom" /> <Button x:Name="button2" Content="button" DockPanel.Dock="Left"/> <Button Name="btn1" Content="button2" DockPanel.Dock="Right"/> <Button x:Name="button3" Content="Button" DockPanel.Dock="Top" /> </DockPanel>
開發人員也可以使用Margin、HorizontalAlignment、VerticalAlignment、屬性來控制子元素的顯示方式
<DockPanel LastChildFill="False"> <Button x:Name="button" Content="Button" DockPanel.Dock="Top" HorizontalAlignment="Center" /> <Button x:Name="button1" Content="Button" DockPanel.Dock="Bottom" /> <Button x:Name="button2" Content="button" DockPanel.Dock="Left"/> <Button Name="btn1" Content="button2" DockPanel.Dock="Right"/> <Button x:Name="button3" Content="Button" DockPanel.Dock="Top" /> </DockPanel>