概述
本文描述几款WPF中常用的布局控件。
Grid
Grid是WPF最常用的布局控件。 它把面板分割为固定长和宽的网格,子控件就放置在网格内。
<Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="100"/> <ColumnDefinition Width="*"/> <ColumnDefinition Width="2*"/> </Grid.ColumnDefinitions> <TextBlock Text="hello" Grid.Column="0" Grid.ColumnSpan="2" HorizontalAlignment="Center" Margin="10"/> </Grid>
Grid控件有两个显著的特点:
1、行高和列宽可以设定为固定值,也可以按比例分配;
2、可以跨行或跨列。
StackPanel
StackPanel按顺序依次排列控件,通过Orientation="Horizontal"或Orientation="Vertical"来控制列表的方向。
<StackPanel Orientation="Horizontal"> <TextBlock Text="Hello"/> </StackPanel>
GridSplitter
通过GridSplitter可以调整两个网格的宽度或高度。
<Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" MinWidth="150"/> <ColumnDefinition Width="3"/> <ColumnDefinition Width="2*" MinWidth="200"/> </Grid.ColumnDefinitions> <Grid Grid.Column="0" Background="WhiteSmoke"/> <GridSplitter Grid.Column="1" Background="CornflowerBlue"/> <Grid Grid.Column="2" Background="LightGray" /> </Grid>
GridSplitter的宽度和颜色都可以设置。
DockPanel
DockPanel控件可以在主要的显示面板周五显示可以停靠的面板。
<DockPanel> <Grid Width="200" DockPanel.Dock="Left" Background="SeaGreen" Visibility="{Binding LeftVisibility}"/> <Grid Width="200" DockPanel.Dock="Right" Background="Orchid" Visibility="{Binding RightVisibility}"/> <Grid Background="Silver"> <Grid.ColumnDefinitions> <ColumnDefinition Width="100"/> <ColumnDefinition Width="*"/> <ColumnDefinition Width="100"/> </Grid.ColumnDefinitions> <Button Grid.Column="0" Content="Left" Width="80" Height="30" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="5" Command="{s:Action LeftClick}"/> <Button Grid.Column="2" Content="Right" Width="80" Height="30" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="5" Command="{s:Action RightClick}"/> </Grid> </DockPanel>
需要注意的是,主面板一定要放在最后描述。通过下面代码可以显示或隐藏Dock面板:
public class PageLayoutViewModel : Screen { public bool IsLeftShow { get; set; } = true; public bool IsRightShow { get; set; } = true; public Visibility LeftVisibility => IsLeftShow ? Visibility.Visible : Visibility.Collapsed; public Visibility RightVisibility => IsRightShow ? Visibility.Visible : Visibility.Collapsed; public void LeftClick() { IsLeftShow = !IsLeftShow; } public void RightClick() { IsRightShow = !IsRightShow; } }View Code
DockPanelSplitter
有没有既可以停靠又可以调整宽度的面板呢?官方没有提供,但git上有。
下载地址:JVimes/DockPanelSplitter: Like WPF's GridSplitter, but for DockPanel instead of Grid. (github.com)
资源
系列目录:WPF开发快速入门【0】前言与目录
代码下载:Learn WPF: WPF学习笔记 (gitee.com)
标签:控件,入门,布局,Visibility,WPF,面板,public,IsRightShow From: https://www.cnblogs.com/seabluescn/p/16539591.html