Silverlight instantiates a CLR object in a XAML Resource

Source: Internet
Author: User

You can create an object of the existing type (or custom type in the user project) in the. NET base class library in the resource. WhenProgramThey are automatically instantiated at runtime.

Example:

Create a student class first.

 Public   Class Student
{
Public String Name
{
Get ;
Set ;
}
Public Bool Isfemale
{
Get ;
Set ;
}

Public Override String Tostring ()
{
If (Isfemale)
Return Name + " : Female " ;
Else
Return Name + " : Male " ;
}

Public Static String Staticinformation = " I am a static field defined by student type! " ;
}

 

In the main form, first introduce the namespace where the student class is located, and define a "Local:" prefix for it;

Xmlns: Local = "CLR-namespace: usecustomizeclass"

 

Then, create a student object in the resource and initialize its attributes: (The following is the XAML of WPF, And the SL class is the same)

<Window. Resources>
<Local: StudentName= "James"Isfemale= "False"X: Key= "Student1"/>

</Window. Resources>

Now you can use this resource in the form.CodeUse the XAML extension to mark "X: static" to access the static field of the student class:

 

     <  Stackpanel Margin  = "10"  > 
< Button Margin = "10" Click = "Button_click" > C # access the attributes of the student object saved in the resource using code </ Button >
< Textblock Horizontalalignment = "Center" Text =" {X: static local: Student. staticinformation} " />
</ Stackpanel >

 

 

Use the C # code to obtain the reference of the student object and then access its instance attributes: (the WPF sample code is similar to the SL class)

 

Private VoidButton_click (ObjectSender, routedeventargs E)
{
Student Stu =This. Findresource ("Student1")AsStudent;
If(Stu! =Null)
MessageBox. Show (STU. tostring ());
}

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.