WPF中的容器控件包括Canvas,Grid,StackPanel,DockPanel
Canvas是一个传统的布局方式,利用它可以定义一个区域,可以在这个区域中创建其他的xmal元素,例如在一个Canvas中添加一个Rectangle元素,并且可以设置相对于Canvas的位置.
例如创建一个Canvas,然后在其中添加两个Rectangle对象,向Canvas对象添加xaml元素使用 Canvas对象中的Children.Add("元素的x:Name"),
在xaml中使用Canvas.Left,Canvas.Top,Canvas.Right,Canvas.Bottom确定相对于Canvas的位置,当确定Canvas.Left和Canvas.Top后,其他两个不起作用.
此例先用xaml创建一个Canvas,然后想其中添加一个绿色的Rectangle元素,再通过后台代码添加一个蓝色的Rectangle元素
<Window x:Class="WpfApplication2.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 x:Name="CanvasParent" Width="300" Height="180" Background="Red"> <Rectangle Fill="Green" Canvas.Left="10" Canvas.Top="10" Width="50" Height="50" Canvas.Bottom="50" Canvas.Right="50"></Rectangle> </Canvas> </Window>
下面是后台代码:
/// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); Rectangle rect = new Rectangle(); rect.Width = 80; //设置宽度 rect.Height = 80; //设置高度 rect.Fill = new SolidColorBrush(Colors.Blue); Canvas.SetLeft(rect, 90); //设置相对左侧位置 Canvas.SetTop(rect, 90); //设置相对顶部位置 CanvasParent.Children.Add(rect); //把rect添加到CanvasParent中 } }
运行结果: