WPF布局——布局面板Canvas
WPF——Canvas布局控件
Canvas(画布) 是WPF中最简单的布局控件,是用于存储控件的容器,不会自动调整内部元素的排列及大小,它仅支持用显式坐标定位控件。可以使用Left
、 Top
、Right
和Bottom
附加属性在Canvas中定位控件。实质上,在选择每个控件停靠角时,附加属性的值是作为外边距使用的。如果一个控件没有使用任何附加属性,它会被放在Canvas的左上方(等同于设置Left
和Top
为0)。
Canvas实例——五个按钮
此例设计要求:将五个Button按钮分别放在画布的左上角、右上角、左下角、右下角和中心位置。
依旧是在VS2019中新建一个WPF项目解决方案WpfApp3:命名项目名字Canvas_Button5。
效果图:
“画布”上的元素附加属性Canvas.Left
、Canvas.Top
、Canvas.Right
和Canvas.Bottom
来完成内部子元素(Button)的定位。这里的Canvas.Left和Canvas.Top属性与Windows Form窗体控件的Left和Top属性类似,Canvas.Left属性表示距离“画布”左边的距离,而Canvas.Top属性表示距离“画布”顶部的距离。
实现代码:
<Window x:Class="Canvas_Button5.MainWindow"
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:Canvas_Button5"
mc:Ignorable="d"
Title="MainWindow" Height="270" Width="480">
<Canvas Width="300" Height="150" Background="PapayaWhip">
<Button Content="Left, Top" Canvas.Left="4" Canvas.Top="4"/>
<Button Content="Right, Top" Canvas.Right="4" Canvas.Top="4"/>
<Button Content="Left, Bottom" Canvas.Left="4" Canvas.Bottom ="4"/>
<Button Content="Right, Bottom" Canvas.Right="4" Canvas.Bottom="4"/>
<Button Content="Center" Canvas.Left="125" Canvas.Top="63"/>
</Canvas>
</Window>
Canvas实例——矩形重叠
此例设计要求:分别将黄色、粉红色和蓝紫色3个Rectangle放到画布上。新建项目Canvas_Rec。
效果图:
“画布”上的元素附加属性Panel.ZIndex设置不同颜色的Rectangle声明的先后顺序,从视觉效果上看,后声明的蓝紫色矩形将先声明的矩形框覆盖,用专业术语则是Panel.ZIndex设置重叠深度。其实Canvas还是沿用了父类Panel的属性。
实现代码:
<Window x:Class="Canvas_Rec.MainWindow"
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:Canvas_Rec"
mc:Ignorable="d"
Title="MainWindow" Height="290" Width="480">
<Canvas>
<Rectangle Panel.ZIndex="3" Width="100" Height="100" Canvas.Top="30" Canvas.Left="30" Fill="BlueViolet" />
<Rectangle Panel.ZIndex="1" Width="100" Height="100" Canvas.Top="70" Canvas.Left="70" Fill="Yellow" />
<Rectangle Panel.ZIndex="2" Width="100" Height="100" Canvas.Top="110" Canvas.Left="110" Fill="Pink" />
</Canvas>
</Window>
相关阅读
上一篇:WPF编程基础入门 ——— 第三章 布局(一)布局原则.
下一篇:WPF编程基础入门 ——— 第三章 布局(三)布局面板DockPanel.
WPF编程基础入门 ——— 目录导航.