By using xamlreader Class Load Method. This method requires a string type XAML CodeSegment. Xamlreader. Load The method creates a control in the memory. If the control is successfully created, Object Type reference, which is converted to the required type through type conversion. If creation fails Null . Use the following sample code XAML The Code creates a rectangle as follows:
Using system;
Using system. windows;
Using system. Windows. controls;
Using system. Windows. documents;
Using system. Windows. Ink;
Using system. Windows. input;
Using system. Windows. Media;
Using system. Windows. Media. animation;
Using system. Windows. shapes;
Namespace createuifromxamlsnippt
{
Public partial class page: canvas
{
Rectangle RC1;
Public void page_loaded (Object o, eventargs E)
{
// Required to initialize Variables
Initializecomponent ();
Createrectanglefromxaml (100,100,200,200 );
//To reference dynamically created controls, useFindname.
RC1 = This. findname ("RC1") as rectangle;
Rc1.mouseleftbuttondown + = new mouseeventhandler (rc1_mouseleftbuttondown );
}
//Defines the click behavior of a rectangle
Void rc1_mouseleftbuttondown (Object sender, mouseeventargs E)
{
Rc1.fill = new solidcolorbrush (colors. Blue );
}
//SlaveXAMLDynamically create a rectangle in the code
Private void createrectanglefromxaml (Double X, Double Y, double W, double H)
{
// XAMLCode
String S = "<rectangle name = 'rc1 'canvas. left = '"+ x +"' canvas. top = '"+ Y +"' "+" width = '"+ W +" 'height =' "+ H +" 'fill = 'red'/> ";
//UseXamlreaderClass to create a rectangle
Rectangle rc = (rectangle) xamlreader. load (s );
//Add to root canvas
This. Children. Add (RC );
}
}
}
to reference a dynamically created control, note that you cannot use X: Name in XAML Code X: Name attribute, by specifying the name attribute for it, use the findname method to reference dynamically created controls.