Dynamically add layout objects and elements to the canvas
Front-endCode:
< Usercontrol X: Class = "Silverlightapplication45.mainpage"
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"
MC: ignorable = "D"
D: designheight = "640" D: designwidth = "400" >
< Grid X: Name = "Layoutroot" >
< Canvas X: Name = "Parentcanvas" Background = "Slategray" >
< Textbox X: Name = "Tbleft" Fontsize = "18" Width = "80" Height = "30" Text = "0"
Canvas. Left = "530" Canvas. Top = "60" />
< Textbox X: Name = "Tbtop" Fontsize = "18" Width = "80" Height = "30" Text = "0"
Canvas. Left = "530" Canvas. Top = "140" />
< Textblock Text = "Canvas. Left :" Fontsize = "18" Canvas. Left = "500" Canvas. Top = "20" />
< Textblock Text = "Canvas. Top :" Fontsize = "18" Canvas. Left = "500" Canvas. Top = "100" />
< Button X: Name = "Btnadd" Content = "Add" Width = "100" Height = "40" Fontsize = "18"
Canvas. Left = "520" Canvas. Top = "200" Click = "Btnadd_click" />
< Button X: Name = "Btnclear" Content = "Clear" Width = "100" Height = "40" Fontsize = "18"
Canvas. Left = "520" Canvas. Top = "280" Click = "Btnclear_click" />
</ Canvas >
</ Grid >
</ Usercontrol >
Background code:
Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. net;
Using System. windows;
Using System. Windows. controls;
Using System. Windows. documents;
Using System. Windows. input;
Using System. Windows. Media;
Using System. Windows. Media. animation;
Using System. Windows. shapes;
Namespace Silverlightapplication45
{
Public Partial Class Mainpage: usercontrol
{
Private Canvas mycanvas = New Canvas ();
Public Mainpage ()
{
Initializecomponent ();
Mycanvas. Width = 480 ;
Mycanvas. Height = 400 ;
Mycanvas. Background = New Solidcolorbrush (colors. Red );
This . Parentcanvas. Children. Add (mycanvas );
}
Private Void Btnadd_click ( Object Sender, routedeventargs E)
{
Ellipse myell = New Ellipse ();
Myell. Width = 40 ;
Myell. Height = 40 ;
Myell. strokethickness = 3 ;
Myell. Stroke = New Solidcolorbrush (colors. Black );
Myell. Fill = New Solidcolorbrush (colors. Green );
Canvas. setleft (myell, convert. todouble ( This . Tbleft. Text ));
Canvas. settop (myell, convert. todouble ( This . Tbtop. Text ));
Mycanvas. Children. Add (myell );
}
Private Void Btnclear_click ( Object Sender, routedeventargs E)
{
Mycanvas. Children. Clear ();
}
}
}