Canvas、StackPanel、WrapPanel、DockPanel和Grid是WPF中主要的5种内建面板,这些面板类都位于System.Windows.Controls命名空间下。

      Canvas是最基本的面板,它仅支持用显式坐标定位元素,它也允许指定相对任何角的坐标,而不仅仅是左上角。可以使用Left、Top、Right、Bottom附加属性在Canvas中定位元素。通过设置Left和Right属性的值表示元素最靠近的那条边,应该与Canvas左边缘或右边缘保持一个固定的距离,设置Top和Bottom的值也是类似的意思。实质上,你在选择每个元素停靠的角时,附加属性的值是作为外边距使用的。如果一个元素没有使用任何附加属性,它会被放在Canvas的左上角(等同于设置Left和Top为0)。

      在Canvas中布置按钮:

<Window x:Class="WPFR.MainWindow"
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Canvas>
        <Button Background="Red">Left=0,Top=0</Button>
        <Button Canvas.Left="18" Canvas.Top="18" Background="Orange">Left=18,Top=18</Button>
        <Button Canvas.Right="18" Canvas.Bottom="18">Right=18,Bottom=18</Button>
        <Button Canvas.Right="0" Canvas.Bottom="0" Background="Lime">Right=0,Bottom=0</Button>
        <Button Canvas.Right="0" Canvas.Top="0" Background="Blue">Right=0,Top=0</Button>
        <Button Canvas.Left="0" Canvas.Bottom="0" Background="Aqua">Left=0,Bottom=0</Button>     
    </Canvas>
</Window>

运行结果如下图所示:

WPF中的5种内建面板之一——Canvas

      元素不能使用两个以上的Canvas附加属性,如果同时设置Canvas.Left和Canvas.Right属性,那么后者将会被忽略。因此,一个元素一次不能停靠多于两个Canvas的角。虽然Canvas太原始,不能用来创建灵活的用户界面,但是它是最轻量级的面板。当真的需要对元素的位置做准确的控制时,应该注意使性能最大化,例如,Canvas对于矢量图形中原始形状的准确定位非常有用。

转载于:https://www.cnblogs.com/Jennifer/articles/1987693.html

相关文章:

  • 2021-12-04
  • 2022-12-23
  • 2022-12-23
  • 2021-10-31
  • 2021-08-24
  • 2021-06-20
  • 2021-06-26
  • 2021-09-21
猜你喜欢
  • 2021-07-11
  • 2021-11-23
  • 2021-12-12
  • 2021-06-04
  • 2021-11-16
相关资源
相似解决方案