布局控件
- 常用布局控件
- Panel基類
- Grid(網格)
- UniformGrid(均勻分布)
- StackPanel(堆積面板)
- WrapPanel(換行面板)
- DockerPanel(停靠面板)
- Canvas(畫布布局)
- Border(邊框)
- GridSplitter(分割窗口)
常用布局控件
- Grid:網格,根據自定義行和列來設置控件的布局
- StackPanel:棧式面板,包含的元素在豎直或水平方向排成一條直線
- WrapPanel:自動折行面板,包含的元素在排滿一行后,自動換行
- DockPanel:泊靠式面板,內部的元素可以選擇泊靠方向
- UniformGrid:網格,UniformGrid就是Grid的簡化版,每個單元格的大小相同
- Canvas:畫布,內部元素根據像素為單位絕對坐標進行定位。
- Border:裝飾的控件,此控件用于繪制邊框及背景,在Border中只能有一個子控件
這里除了Border控件,其他控件都繼承于Panel基類。
Panel基類
所有Panel元素都支持FrameworkElement定義的基本大小調整和定位屬性,包括Height、Width、HorizontalAlignment、VerticalAlignment、Margin和LayoutTransform。Panel公開對了解和使用布局至關重要的其他屬性。Background屬性用于借助Brush填充派生面板元素的邊界之間的區域。Children表示組成Panel的子元素集合。InternalChildren表示Children集合的內容以及由數據綁定生成的成員。兩者均由父Panel內承載的子元素的UIElementCollection組成。
Panel提供了附加屬性,ZIndex。假如一個單行單列的Grid布局控件中有兩個Button,正常情況下,這兩個Button都會以撐滿Grid中,那么到底哪一個Button在上面,哪一個在下面。就看這兩個Button的Panel.ZIndex附加屬性的值,值越大的在上面,而值較小的那個Button將被上面的Button遮蓋,從而在視覺上,用戶只能看到一個Button。
<Grid Background="AliceBlue" PreviewMouseUp="Grid_PreviewMouseUp"><Button Panel.ZIndex="2" Content="按鈕1" Width="200" Height="30"/><Button Panel.ZIndex="0" Content="按鈕2" Width="200" Height="30"/></Grid>
Grid(網格)
Grid控件是WPF中所有布局控件中最好用的一個,因為它是自適應屏幕的寬度,最關鍵的一點是,它在呈現時,其ActuaWidth實際寬度和ActualHeight實際高度會有一個計算值,我們在業務開發中,有時候要根據父控件的實際寬度和高度來計算子控件的呈現位置和大小。
<Window x:Class="WpfApp1.MyGrid"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:WpfApp1"mc:Ignorable="d"Title="MyGrid" Height="450" Width="800"><!--展示線條--><Grid ShowGridLines="True"><!--三行--><Grid.RowDefinitions><RowDefinition Height="*" /> <!--Height="100" 固定高度--><RowDefinition Height="2*"/> <!--Height="2*" 等比例的高度--><RowDefinition Height="2*"/> <!--Height="Auto" 跟隨文本的高度--></Grid.RowDefinitions><!--兩列--><Grid.ColumnDefinitions><ColumnDefinition/><ColumnDefinition Width="Auto"/> <!--Width="Auto" 跟隨文本的寬度--></Grid.ColumnDefinitions><!--第一行第一列--><!--Grid.RowSpan="2" 合并單元格行--><TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Grid.RowSpan="2" Text="文本1" Grid.Row="0" Grid.Column="0" FontSize="30"/><!--第一行第二列--><TextBlock Text="文本2" Grid.Row="0" Grid.Column="1" FontSize="30"/><!--<TextBlock Text="文本3" Grid.Row="1" Grid.Column="0" FontSize="30"/>--><TextBlock Text="文本4" Grid.Row="1" Grid.Column="1" FontSize="30"/><!--Grid.ColumnSpan="2" 合并單元格列--><TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Grid.ColumnSpan="2"Text="文本5" Grid.Row="2" Grid.Column="0" FontSize="30"/><!--<TextBlock Text="文本6" Grid.Row="2" Grid.Column="1" FontSize="30"/>