asp.net2.0 a server control's typed style properties

Source: Internet
Author: User
Tags bool constructor empty implement reset
Asp.net| Server | control

   on an articleThis article describes the basic concepts of control style properties, and also illustrates how to override style properties by example. This article focuses on the method of creating typed style attributes.

   ways to implement typed style properties

Classes that inherit from the style class are called typed styles. Style classes can be extended by control developers, creating a custom typed style that overrides or adds properties of the style class. Server controls can also use custom typed styles as the type of the ControlStyle property. For example, the ControlStyle property of a Table control is the TableStyle type, which is an extended style that adds such as cellpadding, cellspacing, and gridlines properties. After preliminary understanding of the basic concepts of typed style properties, the following is an outline of how to implement typed style properties.

(1) Create a class derived from System.Web.UI.WebControls.Style;

(2) Defines the properties that the style will provide for the control. Save the property in the ViewState dictionary of Style;

(3) Rewriting the CopyFrom and Mergewith methods, copying from the defined properties or merging the defined attributes with the properties of a given style;

(4) Rewrite the Reset method to remove the attributes added to the ViewState;

(5) Rewrite the AddAttributesToRender method to produce HTML and CSS attributes as part of the control rendering process.

In fact, creating a typed style property is not a straightforward process. To do this, we will use the typical application examples to illustrate the specific methods of creation, so that readers can deepen their understanding of the implementation essentials.

   Typical Applications

This section explains how to implement and use a custom typed style by creating a Mypanel control and associated typed style mypanelstyle. In terms of functionality, Mypanel is consistent with the ASP.net 2.0 built-in panel control. Developers can add controls to the Controls collection by nesting the controls that need to be added to the label of the control. In the visual designer, you can add controls to the Controls collection by dragging and dropping the controls you want to add to the design interface of the panel. However, Mypanel does not inherit from the Panel class, but rather the result of a custom implementation, and the control also provides a typed style property myPanelStyle with 3 style properties set:

(1) Backimageurl, used to specify the URL of the background picture;

(2) HorizontalAlign, used to specify the level of the added content on its way;

(3) Wrap, which specifies whether to allow wrapping of the added content.

The example effect diagram is listed below.


Figure 1


As shown in Figure 1, the figure shows a Mypanel control that includes a line of text, the background image of the text is defined, and the text is centered.

The MyPanel.cs source code that implements the custom server control is listed below.

Using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Text;
Using System.Web;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Namespace webcontrollibrary{
[ParseChildren (False), PersistChildren (true)]
[ToolBoxData ("<{0}:mypanel runat=server> </{0}:MyPanel>")]

public class Mypanel:webcontrol {
Defining constructors
Public Mypanel (): Base (Htmltextwritertag.div) {}
Implement Properties Backimageurl
[Bindable (True)] [Category ("appearance")]
[DefaultValue ("")]

Public virtual string Backimageurl {
get {
if (controlstylecreated) {
Return ((myPanelStyle) ControlStyle). Backimageurl;
}
return String.Empty;
}
set {
((myPanelStyle) ControlStyle). Backimageurl = value;
}
}
Implement Properties HorizontalAlign
[Bindable (True)]
[Category ("Layout")]
[DefaultValue ("")]

Public virtual HorizontalAlign HorizontalAlign {
get {
if (controlstylecreated) {
Return ((myPanelStyle) ControlStyle). Horizonalalign;
}
return horizontalalign.notset;
}
set {
((myPanelStyle) ControlStyle). Horizonalalign = value;
}
}
Implement Properties Wrap

[Bindable (True)]
[Category ("Layout")]
[DefaultValue ("")]

Public virtual bool Wrap {
get {
if (controlstylecreated) {
Return ((myPanelStyle) ControlStyle). Wrap;
}
return true;
}
set {
((myPanelStyle) ControlStyle). Wrap = value;
}
}
protected override Style Createcontrolstyle () {
return new myPanelStyle (ViewState);
}
}
}
Before the analysis, in order to help readers better read the above source code, the following list of Mypanel class diagram.


Figure 2


As the previous code shows, Mypanel inherits from the WebControl base class, which defines 3 properties Backimageurl, HorizontalAlign, and wrap. For a description of these 3 attributes, the reader can refer to the previous section. In addition, Mypanel overrides the Createcontrolstyle method and returns a myPanelStyle object. The returned myPanelStyle instance is indirectly assigned to the ControlStyle property. The reason for this implementation is that the ControlStyle property is read-only and its access operation needs to be set by calling the Createcontrolstyle method time. The reader should note that Createcontrolstyle passes the viewstate of the Mypanel control to the myPanelStyle constructor. When you create a new style for a control in Createcontrolstyle, you must pass the control's viewstate to the style constructor, and the style object uses the same statebag as the control.

The following is a list of the source code that implements the myPanelStyle class, which comes from the MyPanelStyle.cs file.

Using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Text;
Using System.Web;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Namespace webcontrollibrary{
public class Mypanelstyle:style {
Defining internal constants
Internal const int Prop_backimageurl = 1;
Internal const int prop_horizontalalign = 2;
Internal const int PROP_WRAP = 3;
A constructor function
Public myPanelStyle () {}
Constructor two
Public myPanelStyle (StateBag bag): Base (bag) {}
Create Backimageurl Property
[Bindable (True), Category ("appearance"), DefaultValue (""), Description ("URL of background picture"), Notifyparentproperty (true)]
Public virtual string Backimageurl {
get {
if (IsSet (Prop_backimageurl)) {
Return (String) viewstate["Backimageurl"];
}
return String.Empty;
}
set {
viewstate["Backimageurl"] = value;
}
}
Implementing the Horizonalalign Property
[Bindable (True), Category ("Layout"), DefaultValue (Horizontalalign.notset), Description ("level of added content to its way"), Notifyparentproperty (True)]
Public virtual HorizontalAlign Horizonalalign {
get {
if (IsSet (prop_horizontalalign)) {
Return (horizontalalign) viewstate["HorizontalAlign"];
}
return horizontalalign.notset;
}
set {
if (Value Horizontalalign.notset | | | value > horizontalalign.justify) {
throw new ArgumentOutOfRangeException ("value");
}
viewstate["horizontalalign"] = value;
}
}
Implement IsEmpty
Protected new internal BOOL IsEmpty {
get {
Return base. IsEmpty &&! IsSet (prop_backimageurl) &&! IsSet (prop_horizontalalign) &&! IsSet (Prop_wrap);
}
}
Implementing the Wrap Property
[Bindable (True), Category ("Layout"), DefaultValue (True), Description ("Do you want to allow line wrapping for added content"), Notifyparentproperty (true)]
Public virtual bool Wrap {
get {
if (IsSet (Prop_wrap)) {return (bool) viewstate["WRAP"];}
return true;
}
set {viewstate["Wrap"] = value;}
}
Auxiliary method Isset
internal BOOL IsSet (int propnumber) {
string key = null;
Switch (propnumber) {
Case Prop_backimageurl:key = "Backimageurl";
Break
Case Prop_horizontalalign:key = "horizontalalign";
Break
Case Prop_wrap:key = "WRAP";
Break
}
if (key!= null) {
return Viewstate[key]!= null;
}
return false;
}
Overriding the AddAttributesToRender method
public override void AddAttributesToRender (HtmlTextWriter writer, WebControl owner) {
if (IsSet (Prop_backimageurl)) {
string s = Backimageurl;
if (S.length > 0) {
if (owner!= null) {
s = owner. ResolveUrl (s);
}
Writer. AddStyleAttribute (htmltextwriterstyle.backgroundimage, "url" ("+ S +"));
}
}
if (IsSet (prop_horizontalalign)) {
System.Web.UI.WebControls.HorizontalAlign halign = this. Horizonalalign;
if (halign!= System.Web.UI.WebControls.HorizontalAlign.NotSet) {
TypeConverter HAC = Typedescriptor.getconverter (typeof (HorizontalAlign));
Writer. AddAttribute (Htmltextwriterattribute.align, HAC. Converttoinvariantstring (halign));
}
}
if (IsSet (Prop_wrap)) {
BOOL wrap = wrap;
if (! Wrap) {
Writer. AddAttribute (Htmltextwriterattribute.nowrap, "nowwrap");
}
}
Base. AddAttributesToRender (writer, owner);
}
Overriding the CopyFrom method
public override void CopyFrom (Style s) {
if (s!= null) {
Base. CopyFrom (s);
if (S is myPanelStyle) {
myPanelStyle MPs = (myPanelStyle) s;
if (!mps. IsEmpty) {
if (MPs. IsSet (Prop_backimageurl))
This. Backimageurl = MPs. Backimageurl;
if (MPs. IsSet (prop_horizontalalign))
This. Horizonalalign = MPs. Horizonalalign;
if (MPs. IsSet (Prop_wrap))
This. Wrap = MPs. Wrap;
}
}
}
}
Overriding the Mergewith method
public override void Mergewith (Style s) {
if (s!= null) {
if (IsEmpty) {
CopyFrom (s);
Return
}
Base. Mergewith (s);
if (S is myPanelStyle) {
myPanelStyle MPs = (myPanelStyle) s;
if (!mps. IsEmpty) {
if (MPs. IsSet (Prop_backimageurl) &&!this. IsSet (Prop_backimageurl))
This. Backimageurl = MPs. Backimageurl;
if (MPs. IsSet (prop_horizontalalign) &&!this. IsSet (prop_horizontalalign))
This. Horizonalalign = MPs. Horizonalalign;
if (MPs. IsSet (prop_wrap) &&!this. IsSet (Prop_wrap))
This. Wrap = MPs. Wrap;
}
}
}
}
Rewrite Reset method
public override void Reset () {
Base. Reset ();
if (IsEmpty) return;
if (IsSet (Prop_backimageurl))
Viewstate.remove ("Backimageurl");
if (IsSet (prop_horizontalalign))
Viewstate.remove ("HorizontalAlign");
if (IsSet (prop_wrap)) Viewstate.remove ("WRAP");
}
}
}
The myPanelStyle class diagram is listed below.


Figure 3


Some readers may feel that the implementation of the myPanelStyle class is somewhat complicated, however, it is still available. The implementation of this class is done strictly according to the typed style property creation method described earlier.

First, the myPanelStyle class inherits the style class, which is the key to creating typed style properties, and then defines 3 properties Backimageurl, HorizontalAlign, and wrap. These 3 properties support the corresponding style properties in Mypanel. The code then rewrites the AddAttributesToRender method so that the relevant HTML and CSS code is generated exactly when the control renders. It should be noted that the second parameter of the method is not nullable and represents the specific control that owns the style object. Finally, the code rewrites 3 methods from the style, CopyFrom, Mergewith, and reset. The first two methods are rewritten to replicate a given mypanelstyle or to merge a given mypanelstyle with itself. Both of these methods call the base class method and then execute their own logic. The main purpose of rewriting the Reset method is to remove the attribute added to the ViewState, which is similar to the first two methods, calling the base class method and then executing its own logic.

The Default.aspx file source code created to test the Mypanel control is listed below.

<%@ Page language= "C #" autoeventwireup= "true" codefile= "Default.aspx.cs" inherits= "_default"%>
<%@ Register tagprefix= "WCL" assembly= "Webcontrollibrary" namespace= "Webcontrollibrary"%>
! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<title> Typed style properties </title>
<body>
<form id= "Form1" runat= "Server"
<wcl:mypanel id= "Demo1" runat= "Server" backimageurl= "pic1.jpg" horizontalalign= "Center" height= "145" width= "160"
<BR/>
<BR/>
This is the line of text that is in the Mypanel control.
</wcl:MyPanel>
</form>
</body>
As the previous code shows, developers can set the controls that need to be added to the Mypanel label just as they would with a panel control. The controls that are set are automatically displayed, and because of the property settings of the Mypanel control itself, the appearance and style of the display will change accordingly.

   Summary

This article introduces the implementation methods of typed style attributes, and strengthens the reader's understanding of the implementation method through a typical example. In the following article, we will continue to discuss the use of ASP.net 2.0 technology to implement the content of the control client functionality.

Related Article

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.