注意:本文大部分内容为B站视频 WPF基础入门视频 的学习笔记,有条件者可以去三连,个人认为讲的不错
零、Visual Studio常用快捷键
- 注释:选中代码,按
Ctrl+K+C
,注意Ctrl
不要松(所有快捷键都是)
- 取消注释:同上,不过变成
Ctrl+K+U
- 格式化代码(整理代码):
Ctrl+K+F
一、WPF布局容器
1. StackPanel
水平或垂直排列元素、Orientation
属性分别: Horizontal
(水平) / Vertical
(垂直)
默认垂直排列
元素默认居中(如图)
1 2 3 4 5
| <StackPanel Orientation="Horizontal"> <Button Width="100" Height="40" /> <Button Width="100" Height="40" /> <Button Width="100" Height="40" /> </StackPanel>
|

2. WrapPanel
水平或垂直排列元素、针对剩余空间不足会进行换行或换列进行排列
默认水平排列
元素默认不居中(如图为从上往下)
1 2 3 4 5 6 7
| <WrapPanel Orientation="Horizontal"> <Button Width="100" Height="40" /> <Button Width="100" Height="40" /> <Button Width="100" Height="40" /> <Button Width="100" Height="40" /> <Button Width="100" Height="40" /> </WrapPanel>
|

3. DockPanel
根据容器的边界、元素进行Dock.Top、Left、Right、Bottom设置
最后一个元素是否占满剩余空间,LastChildFill
属性分别为True
和False
1 2 3 4 5 6
| <DockPanel LastChildFill="False"> <Button Width="100" Height="40" DockPanel.Dock="Left"/> <Button Width="100" Height="40" DockPanel.Dock="Top"/> <Button Width="100" Height="40" DockPanel.Dock="Right"/> <Button Width="100" Height="40" DockPanel.Dock="Bottom"/> </DockPanel>
|

4. Grid
类似table表格、可灵活设置行列并放置控件元素、比较常用,RowDefinition
为行,ColumnDefinitions
为列
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <Grid> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition/> </Grid.ColumnDefinitions> <Border Background="Red"/> <Border Grid.Column="1" Background="Blue"/> <Border Grid.Row="1" Grid.Column="1" Background="Green"/> <Border Grid.Row="1" Background="Yellow"/> </Grid>
|

定义行和列时可以设置高和宽,当行的Height="auto"
时,行的高度将由其中的元素决定
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <Grid> <Grid.RowDefinitions> <RowDefinition Height="auto"/> <RowDefinition/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition/> </Grid.ColumnDefinitions> <Border Background="Red"/> <Border Grid.Column="1" Background="Blue"/> <Border Grid.Row="1" Grid.Column="1" Background="Green"/> <Border Grid.Row="1" Background="Yellow"/> <Button Height="40">Click Me</Button> </Grid>
|

指定行和列的数量, 均分有限的容器空间
6. Canvas
使用固定的坐标设置元素的位置、不具备锚定停靠等功能。