Create a control from the XAML code

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.