WPF之路——Canvas布局(画布)

 Canvas为容器控件,用于定位

1.基本应用

可以把Canvas比作一个坐标系,所有的元素通过设置坐标来决定其在坐标系中的位置.这个坐标系的原点并不是在中央,而是位于它的左上角.见下图

元素设置坐标的方法共有四个:

        Canvas.Top     设置元素距Canvas顶部的距离

        Canvas.Bottom  设置元素距Canvas底部的距离

        Canvas.Left     设置元素距Canvas左边界的距离

        Canvas.Right    设置元素距Canvas右边界的距离

[html] view plain copy
 
 在CODE上查看代码片派生到我的代码片
<Border HorizontalAlignment="Left" VerticalAlignment="Top" BorderBrush="Black" BorderThickness="2">  
    <Canvas Background="LightBlue" Width="400" Height="400">  
      <Button Canvas.Top="50">Canvas.Top="50"</Button>  
      <Button Canvas.Bottom="50">Canvas.Bottom="50"</Button>  
      <Button Canvas.Left="50">Canvas.Left="50"</Button>  
      <Button Canvas.Right="50">Canvas.Right="50"</Button>  
    </Canvas>  
  </Border>   
 

2.当同时设置left和right,top和bottom,以left和top为准

[html] view plain copy
 
 在CODE上查看代码片派生到我的代码片
<Canvas>  
    <Button Canvas.Left="20" Canvas.Top="20" Width="50" Height="20">button</Button>  
  </Canvas>  


 对比上图,按钮的位置为向右下偏移了一些. 看来Canvas.Top和Canvas.Left起作用了,我们可以得知按钮左上角坐标为(20,20)

    当然还可以从上面的代码中得到更多的信息:

         按钮左下角的坐标 (20,40)

      按钮右上角的坐标 (70,20)

         按钮右下角的坐标 (70,40)

  

我是如何得到这些信息的呢?下面慢慢解释:

按钮左下角坐标的x值和左上角的一样,也为20。其y轴坐标在原有的基础上又增加了一些:加上了按钮的高度.所以得出了(20,40) .后面两个坐标可依此推出。

在同时设置了Canvas.Left和Canvas.Right属性的情况下,只有Canvas.Left属性起作用,而Canvas.Right失效,实际上Canvas.Top和Canvas.Bottom同时存在时也只是Canvas.Top一个起作用

3.重叠深度设置

[html] view plain copy
 
 在CODE上查看代码片派生到我的代码片
<Canvas>  
    <Rectangle Canvas.ZIndex="3" Width="100" Height="100" Canvas.Top="100" Canvas.Left="100" Fill="blue"/>  
    <Rectangle Canvas.ZIndex="1" Width="100" Height="100" Canvas.Top="150" Canvas.Left="150" Fill="yellow"/>  
    <Rectangle Canvas.ZIndex="2" Width="100" Height="100" Canvas.Top="200" Canvas.Left="200" Fill="green"/>  
  
    <!-- Reverse the order to illustrate z-index property -->  
  
    <Rectangle Canvas.ZIndex="1" Width="100" Height="100" Canvas.Top="300" Canvas.Left="200" Fill="green"/>  
    <Rectangle Canvas.ZIndex="3" Width="100" Height="100" Canvas.Top="350" Canvas.Left="150" Fill="yellow"/>  
    <Rectangle Canvas.ZIndex="2" Width="100" Height="100" Canvas.Top="400" Canvas.Left="100" Fill="blue"/>  
  </Canvas>  


原文地址:https://www.cnblogs.com/hushzhang/p/5911748.html