Create a custom control for Silverlight

Source: Internet
Author: User
ArticleDirectory
    • Modify the Silverlight Class Library Project
    • Define the UI in XAML
    • Get object reference in your control
    • Add attribute
    • Test the control.
Introduction

A basic Microsoft Silverlight project assumes that the Extensible Application Markup Language (XAML) file in the current project defines a specific applicationProgramPage. however, a control project uses a XAML file to define the user interface (UI) for all objects that call it. this article describes how to add a file to a basic control project to test the control.

Run View

Requirements (see Silverlight download site ):

    • Microsoft Silverlight 1.1 Alpha.

    • Microsoft Visual Studio code name "orcas" Beta 1.

    • Microsoft Silverlight tools alpha for Visual Studio code name "orcas" Beta 1.

Control UI and Object Model

Creating a control includes two tasks: defining the UI and defining the object model. The UI is mainly defined in The XAML file, while the object model is in the background.CodeFile definition. This will often have interaction between the front-end tag file and the background code, because you may initiallyLoadedThen define handler in the background code file. alternatively, you may construct in XAML or name an existing elements, and then you can get their references in the background code file. in this way, both the code file and the XAML file will be compiled into a library, which can then be used by other applications or projects.

Silverlight Class Library Project

A basic Silverlight Class Library Project template does not have a XAML file, but only one code file. You can add a XAML file as an embedded resource to it.

Modify the Silverlight Class Library Project
    1. Open Visual Studio.FileIn the menu, clickNew projectInNew projectIn the dialog box, selectVisual C #And then selectSilverlightInTemplatesList, selectSilverlight class library.

    2. In Solution Explorer, right-clickClass1.csThen selectDelete.

    3. In Solution Explorer, right-click Project and selectAdd,New item.

    4. InAdd new itemIn the dialog box, selectSilverlight User Control. Name itMylabel. XAMLAnd then clickOKThis will add two files: a XAML file defining the UI, and A. CS file compiling code.

      Note:

      It is more appropriate to add a XAML page for compilation and use it as an embedded resource. The reason is described later.

Define UI

CanvasIs the starting point of a typical control.CanvasThe contents of the root element will affect any application UI that references it.

You have defined various control UIS as the child elements of the XAML root. in the example, you will add only one element, but this will be enough to watch the running of the control. some complex control samples may need to add hundreds of lines of code to the XAML. This includes predefined event-driven-based animations used to collect UI interaction, with deep element nesting, images.

Define the UI in XAML
    1. Open mylabel. XAML to edit. Copy the following XAML contentCanvasMarking the root.

      CS
      <Textblock X: Name = "TB"> </textblock>

      VB
      <Textblock X: Name = "TB"> </textblock>

    2. Save the file.

      In the example of quickstart, all you have done is this. Note:X: NameAttribute. You should generally putX: NameTo any important element, because using name references in the background code file is an important means for you to strictly control the UI control.

Get object references

Before you start to add custom attributes, You need to obtain some references to objects in the XAML so that you can use them in the code file. when you open the background code file, you can see that the class has defined a default constructor. this explains why the XAML file should be treated as an embedded resource: the code file will access the XAML file as a stream from the Assembly resource. this stream will actControlClass MethodInitializefromxamlImportant parameter input string, this method shows how the XAML and its background code files are checked at the very beginning. in fact, the background constructor generated by the template also does some other work:InitializefromxamlActually, there is a returned value. This value will be useful for your reference to various objects in XAML. You can access the object tree in the following process.

Get object reference in your control
  1. Open mylabel. XAML. CS or mylabel. XAML. VB to edit.

  2. Add a nameImplementationrootOfFrameworkelementType Variable. Then changeInitializefromxamlCall to assign the return valueImplementationroot. After you finish this, your code should be the same as the following example.

  3. NextImplementationrootAs the start point of the object tree, you can getTextblockElement references. If you do not callFindnameAnd use "this" or "me "(ControlBase), it is not correct, because the object tree. Object Tree is generated only after the XAML file is loaded. HereTextblockAdd a variable.

    CS
    Textblock TB;

    VB
    Private m_tb as textblock

  4. Add the third line of code to callFindnameThe constructor.Textblock.

    CS
    TB = implementationroot. findname ("TB") as textblock;

    VB
    M_tb = m_implementationroot.findname ("TB ")

Custom properties and events for controls

Normally, the control does not expose any properties or events. you can define public attributes (using public setters) so that you can set the control instance in the Tag file or code file. similarly, you can define shared events. in this Quick Start section, you will follow the exampleFrameworkelementTwo basic appearance and size attributes,HeightAndWidth. You will add two custom attributesMylabel, Which will be appliedTextblockAttribute Value.

Add attribute
  1. In mylabel. XAML. CS or mylabel. XAML. VB, add the height attribute of mylabel , set the implementationroot canvas width. you must hide this attribute because it already exists in Control , but control. height does not have any connection with your control.

    CS
     Public Virtual new double height {get {return implementationroot. height;} set {implementationroot. height = value; updatelayout () ;}

    VB
     Public overridable shadows property height () as Double get return m_implementationroot.height end get set (byval value as double) m_implementationroot.height = value updatelayout () end set end property 

  2. Add an attribute with the New Keyword width to mylabel .

    CS
     Public Virtual new double width {get {return implementationroot. width;} set {implementationroot. width = value; updatelayout () ;}

    VB
     Public overridable shadows property width () as Double get return m_implementationroot.width end get set (byval value as double) m_implementationroot.width = value updatelayout () end set end property 

  3. you need to provide another important attribute to mylabel , which is the display text. define a text attribute to mylabel , in this way, you can set the textblock attribute for your control (the control is and TB references ).

    CS
     Public String text {get {return TB. text;} set {TB. TEXT = value; updatelayout () ;}

    VB
     Public Property text () as string get return m_tb.text end get set (byval value as string) m_tb.text = value updatelayout () end set end property 

  4. You can also define more attributes, such as setting the text color attributes. In this case, you needBrushType forcibly convertedSolidcolorbrushTo avoid the limitations of attribute setting. Of course, the attribute value must comply with the element syntax.

    CS
    Public solidcolorbrush labelcolor {get {return (solidcolorbrush) TB. Foreground;} set {TB. Foreground = (solidcolorbrush) value ;}}

    VB
    Public property labelcolor () as solidcolorbrush get return m_tb.foreground end get set (byval value as solidcolorbrush) m_tb.foreground = directcast (value, solidcolorbrush) end set end property

  5. Save mylabel. XAML. CS (or mylabel. XAML. VB) and build the project.

Currently, you cannot debug or run your project, because your control is only a library and it is not used by other Silverlight pages. next, we will add some test files to your project. an optional method is to create a solutions containing multiple projects, add the assembly of the control project, and then use it.

Test your control and test the control.
  1. A New Visual Studio. create a new basic Silverlight Project (view how to create a Silverlight project ). it doesn't matter how you name it, because you will organize the files in the project and add them to the main project.

  2. Open explorer. go to the project folder you just created. copy these files: default.html, createsilverlight. JS, Silverlight. JS, and page. XAML. in this Quick Start document, you do not need page. XAML. CS.

  3. Navigate to the silverlightcustomcontrol project folder in explorer. paste the four files.

  4. In the Visual Studio program that creates the silverlightcustomcontrol project, open Solution Explorer. Right-click the project and selectAdd,Existing item.

  5. InAdd existing itemIn the dialog box, select four files to paste. ClickOK.

  6. In Solution Explorer, right-click the project and selectProperties.

  7. InPropertiesIn the window, clickDebugColumn. ChangeStart actionIsSpecific page, Set the value to default.html.

  8. Open page. XAML to edit. DeleteX: ClassAttribute andLoadedHandler. (You wocould have needed the code file and a separate build action to support this code, but you do not need any code to merely instantiate your control in XAML .)

  9. Now you need to add a rowXmlnsTo reference your custom control assembly. Add the following attributes to your root tag:

    Xmlns: My = "CLR-namespace: silverlightsamplecontrol; Assembly = clientbin/silverlightsamplecontrol. dll ".

  10. Now adding a specific element will placeMylabelTo your page. But you should add a prefix before the element name.MyIn this way, the compiler knows how to find its definition. You can also setMylabelDefined attribute value.

    CS
    <My: mylabel Height = "30" width = "200" text = "Hello..." labelcolor = "blue"/>

    VB
    <My: mylabel Height = "30" width = "200" text = "Hello..." labelcolor = "blue"/>

  11. Compile and debug the application. You can see the customMylabelIt is displayed. You can also add breakpoints, for exampleMylabelOr add it in handlers to debug the user interaction process.

Hide inherited attributes

The preceding example defines two attributes (HeightAndWidth) They use keywordsNewIntentionally hiding the corresponding attributes of the base class can be seen in other samples of the Silverlight SDK. Hiding attributes is not the best method, but it is currently the only feasible method.ControlSlaveFrameworkelementInheritanceHeightAndWidth,FrameworkelementBut it is unclearControlImplementation Definition of the base class. the XAML attribute tries to set the attribute of the base class. in addition to hiding these attributes from the base class, you should synchronize these attributes before being accessed. in this example,UpdatelayoutThe method is called in the corresponding attribute declaration, and the class constructor also sets the hidden attribute of the base class to synchronize it.

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.