Pro Server Controls and AJAX Components phần 3 pot

77 313 0
Pro Server Controls and AJAX Components phần 3 pot

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

CHAPTER 4 ■ THE WEBCONTROL BASE CLASS AND CONTROL STYLES 129 Visual Studio .NET 2003 included a page property called pageLayout, which enabled precise positioning of server controls when the pageLayout property is set to GridLayout. Visual Studio and ASP.NET 2.0 and later do not have a pageLayout property on web form documents, but there is a similar capability in the HTML designer. Go to Tools ➤ Options, and expand the HTML Designer node. Select the CSS Positioning node, check the option “Change positioning to the following for controls”, and select “Absolutely positioned” in the combo box. Note that this is a global setting that will affect all subsequent web forms. Figure 4-4 shows the Options dialog box. Figure 4-4. The Visual Studio HTML Designer Options dialog box for setting the web form layout to “Absolutely positioned” The “Absolutely positioned” option uses the features of CSS absolute positioning, speci- fying pixel locations for server control objects, as shown in Figure 4-5. Visual Studio translates the developer’s drag-and-drop movements of controls on the Designer surface into CSS style properties. The following server control style properties position a button 133 pixels from the top of the document and 252 pixels from the left edge. <asp:Button id="Button1" style="Z-INDEX: 101; LEFT: 252px; POSITION: absolute; TOP: 133px" runat="server" Text="Button"></asp:Button> CSS absolute positioning is enabled with the position property having an absolute value. The z-index provides a way to position the HTML elements in a third dimension: depth. This allows for overlapping content and some interesting visual effects. Cameron_865-2C04.fm Page 129 Tuesday, January 22, 2008 6:27 AM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 130 CHAPTER 4 ■ THE WEBCONTROL BASE CLASS AND CONTROL STYLES Figure 4-5. A Visual Studio Designer web form using “Absolutely positioned” WebControl and Control Styling Up to this point in this book, we built our server controls by inheriting from System.Web.UI. Control as the base class. We did this to keep things simple, concentrating on the basics of control development. However, Control as a base class starts to show its inherent limitations when we start working with styling and cross-browser support. When inheriting from Control, developers are responsible for manually building up the HTML tags, providing a style property and manually emitting the style property into the HTML output stream. To avoid this work, a better choice is inheriting from the WebControl class, as you will see in the ensuing discussion. ■Note There will be times when inheriting from Control is desired in order to have full control over the rendering process and the capabilities built into WebControl are not required. When this is not the case, we recommend inheriting from WebControl or WebPart discussed later in this book whenever possible. Cameron_865-2C04.fm Page 130 Tuesday, January 22, 2008 6:27 AM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com CHAPTER 4 ■ THE WEBCONTROL BASE CLASS AND CONTROL STYLES 131 In this section, we discuss how to add styling capabilities to server controls. We also intro- duce a new method of building server controls that inherit from the WebControl class. The WebControl class provides an abstraction layer over the rendering process to support strong styling capabilities and rendering in down-level browsers. The WebControl class from the System.Web.UI.WebControls namespace provides a wealth of style support in the form of style properties and automatic style rendering. Not only does it take care of rendering CSS style properties, but it also goes the extra mile to support HTML 3.2 with explicit style tags for down-level browsers. Control styling and rendering are closely coupled, because at the end of the day, raw HTML is the output from a server control. In the next section, we dive into the styling capabilities available in WebControl. Along the way, we discuss the new rendering model in WebControl that provides the necessary support for styling and down-level browsers without requiring too much effort on the developer’s part to make it happen. WebControl’s ControlStyle Property ControlStyle is the property of interest in the WebControl class for manipulating styling. It is a read-only property that provides access to an instance of the System.Web.UI.WebControls.Style class. The Style class captures most of the commonly used style properties that a web devel- oper needs to use with a control, focusing on text, font, color, and borders. Table 4-1 shows the properties that hang from the Style class and the CSS property that is rendered in conjunction with the property. CssClass is a string property that translates directly to rendering a class attribute on the control tag. Setting the CssClass property in the .aspx page for the ASP.NET Label WebControl <asp:label id="myspan" runat="server" CssClass="mycssclass" Text="blank" /> Table 4-1. Properties of the System.Web.UI.WebControls.Style Class Style Property CSS Property BackColor background-color BorderColor border-color BorderStyle border-style BorderWidth border-width CssClass CSS class name Font Font weight, style, family, and so on ForeColor color Height height Width width Cameron_865-2C04.fm Page 131 Tuesday, January 22, 2008 6:27 AM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 132 CHAPTER 4 ■ THE WEBCONTROL BASE CLASS AND CONTROL STYLES translates into the following HTML: <span id="myspan" class="mycssclass">blank</span> The Font property exposes a set of subproperties, so we continue our property examina- tion with Table 4-2 for the System.Web.UI.FontInfo class. WebControl Top-Level Style Properties Going through the ControlStyle property to access these attributes would require a lot of extra typing when setting style properties in either the .aspx control tag or the code-behind class file. The WebControl class makes life easier by exposing all of the properties listed in Tables 4-1 and 4-2 directly as properties (see Figure 4-6), which saves a lot of typing. The top-level property exposure as shown in Figure 4-6 shortens the syntax from this Mycontrol.ControlStyle.ForeColor = red; to the more pleasant MyControl.ForeColor = red; The style properties are also available for configuration of the control tag via attributes in the .aspx page as well: <apress:textbox id="MyControl" runat="server" forecolor="red" font-bold="true" /> These top-level properties are convenient to use, but there are other styling attributes available too numerous to hang off of the WebControl class. Instead, you can access these styling capabilities through the Style property. Table 4-2. Properties of the System.Web.UI.WebControls.FontInfo Class Font Property CSS Property Bold font-weight: bold Italic font-style: italic Name font-family Names font-family Overline text-decoration: overline Size font-size Strikeout text-decoration: line-through Underline text-decoration: underline Cameron_865-2C04.fm Page 132 Tuesday, January 22, 2008 6:27 AM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com CHAPTER 4 ■ THE WEBCONTROL BASE CLASS AND CONTROL STYLES 133 Figure 4-6. WebControl and top-level style properties The Style Property The ControlStyle property and top-level properties of WebControl do not expose the complete spectrum of CSS styling capabilities. The most notable omissions are the placement attributes that allow you to do CSS absolute positioning. To handle these “other” style properties, WebControl exposes a collection via the Style property. The Style property is an instance of type CssStyleCollection. CssStyleCollection is a string-based collection that uses string names as indexers into the values. This is similar to the Hashtable class, except it mandates strings for both keys and values. You can set the Style property programmatically, but it is more commonly set by adding style properties to the .aspx page. The WYSIWYG designers, such as the ASP.NET Designer in Visual Studio in “Absolutely positioned” mode, are the best examples of this. The ASP.NET Designer uses the Style property on the .aspx page to control the layout of the controls when it is set to be absolutely positioned: <asp:button id="Button2" runat="server" style="Z-INDEX: 101; LEFT: 252px; POSITION: absolute;"></asp:button> Cameron_865-2C04.fm Page 133 Tuesday, January 22, 2008 6:27 AM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 134 CHAPTER 4 ■ THE WEBCONTROL BASE CLASS AND CONTROL STYLES Parsing an .aspx page creates start-up code that initializes a control’s Style property collection with declarative style properties. You can modify the Style property programmatically as well. The following line of code changes the button’s text color from its declarative red value to a programmatically set blue value: Button1.Style[color] = blue; The primary drawback to adding style properties via the Style property collection is that it isn’t browser-aware. Although ControlStyle properties render HTML tags for down-level browsers, the Style properties are streamed to the browser verbatim as CSS properties. If the browser doesn’t understand the CSS properties, it simply ignores them. We next move on to discuss how to provide cross-browser compatible styling capabilities by taking advantage of the rendering system provided by the WebControl class. A New Rendering System As we stated earlier, the custom controls we have developed so far inherit from Control and require that we override the Render() method of the base Control class to emit HTML output. Going forward in this chapter, we will inherit from the WebControl class, which overrides Render() by default to save us from having to emit raw HTML tags and style content into the output stream. Instead, we override RenderContents(), which is a method in the WebControl class. RenderContents() provides a method signature identical to that of Render() with an HtmlTextWriter reference as its sole parameter. The difference is that you have the task of emit- ting what is inside the outermost HTML tag for the control. For this reason, you need to let WebControl know what kind of HTML tag formulates your control’s outer shell. You can do this in one of two ways: by passing the tag via the HtmlTextWriterTag enumeration to the base WebControl constructor or by setting either the TagKey or TagName property of WebControl. The more common way is to use the base constructor: public Label() : base(HtmlTextWriterTag.Span) { } In the next section, we dive into WebControl-based control building and create a simple Label control. A Styled Label Control Label controls are probably the simplest controls in the ASP.NET server control arsenal. They have a single mission: to render a piece of content within a <span> tag. To demonstrate the styling powers of the WebControl class, we will build our own version of the Label control. Listing 4-1 shows how easy this truly is. Listing 4-1. The Label Control using System; using System.Web.UI; using System.Web.UI.WebControls; using System.ComponentModel; Cameron_865-2C04.fm Page 134 Tuesday, January 22, 2008 6:27 AM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com CHAPTER 4 ■ THE WEBCONTROL BASE CLASS AND CONTROL STYLES 135 namespace ControlsBook2Lib.Ch04 { [ToolboxData("<{0}:label runat=server></{0}:label>"), DefaultProperty("Text")] public class Label : WebControl { public Label() : base(HtmlTextWriterTag.Span) { } public virtual string Text { get { object text = ViewState["Text"]; if (text == null) return string.Empty; else return (string)text; } set { ViewState["Text"] = value; } } override protected void RenderContents(HtmlTextWriter writer) { writer.Write(Text); } } } The constructor of the Label control calls the base constructor of WebControl to have it emit the content inside of <span> tags via the HtmlTextWriterTag.Span enumeration value. This sets up the control to call our overridden RenderContents() method. Note that we do not emit a single HTML tag directly. The RenderContents() method simply has to write out the Text property to complete the control functionality. We next create a TextBox control to demonstrate further how to work with WebControl, laying the groundwork for building stylized server controls that take full advantage of the capabilities built into ASP.NET and the WebControl class. The AddAttributesToRender() Method The Label was an easy enough control to build, but its limited functionality did not require the use of attributes on the <span> tag. What happens when you have an <input> tag like our various TextBox controls from previous chapters? It needs to output type and value attributes inside the <input> tag. Cameron_865-2C04.fm Page 135 Tuesday, January 22, 2008 6:27 AM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 136 CHAPTER 4 ■ THE WEBCONTROL BASE CLASS AND CONTROL STYLES For those who need to render attributes on the outer tag, the AddAttributesToRender() method is a method override available when inheriting from WebControl that fits the bill. It is part of the customized Render() process that WebControl orchestrates, and it is called by the RenderBeginTag() method of WebControl. The WebControl version of Render() executes the following routines in order, with RenderBeginTag() calling AddAttributesToRender(): • RenderBeginTag() • RenderContents() • RenderEndTag() Figure 4-7 shows the relationship graphically. Figure 4-7. The rendering process in the WebControl class Depending on the level of control required, you can overload each step of the process as necessary. The RenderBeginTag()/RenderEndTag() method pairs are less commonly overloaded, because they do the outer tag rendering by looking up the TagKey or TagName property values and emitting the content via HtmlTextWriter. The key point to remember is that when you override AddAttributesToRender(), you must also call the base WebControl version of the method to ensure that the style properties managed by WebControl are emitted properly: base.AddAttributesToRender(writer); Also, you can use HtmlTextWriter and its AddAttribute() method to add other attributes as necessary: writer.AddAttribute("value",Text); Now that we have covered the basics of inheriting from WebControl, we can move on to add style capabilities to our TextBox control from earlier in this book. A Styled TextBox Control In this section, we bring back our favorite TextBox control from chapters past and update it with WebControl capabilities. As you would guess, most of the implementation remains the same. The biggest changes relate to how we handle the rendering process. Cameron_865-2C04.fm Page 136 Tuesday, January 22, 2008 6:27 AM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com CHAPTER 4 ■ THE WEBCONTROL BASE CLASS AND CONTROL STYLES 137 The first step in updating TextBox is to inherit from WebControl and set the constructor to create the tag for the outer shell of the control. The following code snippet sets up our WebControl version of the TextBox to render an <input> tag: public class Textbox : WebControl, IPostBackDataHandler { public Textbox() : base(HtmlTextWriterTag.Input) { } } The rendering code in this version of TextBox is dramatically smaller than the previous version that inherited from Control. All we have to implement is the AddAttributesToRender() method to set the <input> tag with the appropriate attributes, and we need to call the base class version to add the style properties: override protected void AddAttributesToRender(HtmlTextWriter writer) { writer.AddAttribute("type","text"); writer.AddAttribute("name",UniqueID); writer.AddAttribute("value",Text); base.AddAttributesToRender(writer); } Listing 4-2 shows the full code for the TextBox control. Listing 4-2. The TextBox Control using System; using System.Web.UI; using System.Web.UI.WebControls; using System.Collections.Specialized; using System.ComponentModel; namespace ControlsBook2Lib.Ch04 { [ToolboxData("<{0}:textbox runat=server></{0}:textbox>"), DefaultProperty("Text")] public class Textbox : WebControl, IPostBackDataHandler { public Textbox() : base(HtmlTextWriterTag.Input) { } public virtual string Text { get Cameron_865-2C04.fm Page 137 Tuesday, January 22, 2008 6:27 AM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 138 CHAPTER 4 ■ THE WEBCONTROL BASE CLASS AND CONTROL STYLES { object text = ViewState["Text"]; if (text == null) return string.Empty; else return (string)text; } set { ViewState["Text"] = value; } } public bool LoadPostData(string postDataKey, NameValueCollection postCollection) { string postedValue = postCollection[postDataKey]; if (!Text.Equals(postedValue)) { Text = postedValue; return true; } else return false; } public void RaisePostDataChangedEvent() { OnTextChanged(EventArgs.Empty); } private static readonly object TextChangedKey = new object(); public event EventHandler TextChanged { add { Events.AddHandler(TextChangedKey, value); } remove { Events.RemoveHandler(TextChangedKey, value); } } Cameron_865-2C04.fm Page 138 Tuesday, January 22, 2008 6:27 AM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [...]... override the CreateChildControls() method so we can populate the internal Controls collection with our child controls InputBox adds the Label and TextBox controls, in that order: override protected void CreateChildControls() { ControlsBookLib.Ch04.Label label = new ControlsBookLib.Ch04.Label(); Controls. Add(label); ControlsBookLib.Ch04.Textbox textbox = new ControlsBookLib.Ch04.Textbox(); Controls. Add(textbox);... Text property value by casting to the appropriate type: public string LabelText { get { EnsureChildControls(); ControlsBookLib.Ch04.Label label = (ControlsBookLib.Ch04.Label) Controls[ 0]; return label.Text; } set { EnsureChildControls(); ControlsBookLib.Ch04.Label label = (ControlsBookLib.Ch04.Label) Controls[ 0]; label.Text = value; } } public string TextboxText { get { EnsureChildControls(); ControlsBookLib.Ch04.Textbox... ControlCollection Controls { get { EnsureChildControls(); return base .Controls; } } private void PrepareControlHierarchy() { ControlsBook2Lib.Ch04.Label label = (ControlsBook2Lib.Ch04.Label )Controls[ 0]; label.ApplyStyle(LabelStyle); label.MergeStyle(ControlStyle); ControlsBook2Lib.Ch04.Textbox textbox = (ControlsBook2Lib.Ch04.Textbox )Controls[ 1]; textbox.ApplyStyle(TextboxStyle); textbox.MergeStyle(ControlStyle);... each of our child controls so that it can apply style properties: private void PrepareControlHierarchy() { ControlsBookLib.Ch04.Label label = (ControlsBookLib.Ch04.Label) Controls[ 0]; label.ApplyStyle(LabelStyle); label.MergeStyle(ControlStyle); ControlsBookLib.Ch04.Textbox textbox = (ControlsBookLib.Ch04.Textbox) Controls[ 1]; textbox.ApplyStyle(TextboxStyle); textbox.MergeStyle(ControlStyle); } The... ContentPlaceHolderID="ChapterNumAndTitle" runat= "server" > 4   WebControl Base Class and Control Styles Web Control Style Enter your... style properties to load all their attributes This ensures that the TextBox is decorated with its TextBoxStyle properties and the Label is decorated with its LabelStyle properties The parent InputBox ControlStyle style is then merged using MergeStyle() to fill in any style properties that are not set by the custom styles If there aren’t any custom style properties selected, the ControlStyle properties... } public string LabelText { get { EnsureChildControls(); ControlsBook2Lib.Ch04.Label label = (ControlsBook2Lib.Ch04.Label )Controls[ 0]; return label.Text; } set { EnsureChildControls(); ControlsBook2Lib.Ch04.Label label = (ControlsBook2Lib.Ch04.Label )Controls[ 0]; label.Text = value; } } 155 Simpo PDF MergePage 156 Split UnregisteredAM Cameron_865-2C04.fm and Tuesday, January 22, 2008 6:27 Version -... labelStyleState; = textboxStyleState; return state; } override protected void CreateChildControls() { ControlsBook2Lib.Ch04.Label label = new ControlsBook2Lib.Ch04.Label(); Controls. Add(label); ControlsBook2Lib.Ch04.Textbox textbox = new ControlsBook2Lib.Ch04.Textbox(); Controls. Add(textbox); } 157 Simpo PDF MergePage 158 Split UnregisteredAM Cameron_865-2C04.fm and Tuesday, January 22, 2008 6:27 Version - http://www.simpopdf.com... and TextBoxStyle Now that we have code to create the child Label and TextBox controls, as well as code to get and set their Text properties, we can move on to demonstrating how to implement custom styles Both LabelStyle and TextBoxStyle rely on private instances of the Style class to hold style properties The private instance is exposed via a read-only property One of the tasks for this read-only property... composite control to provide custom style properties for its child controls Many of the more advanced list controls, such as the DataGrid in ASP.NET, provide the ability to stylize different settings—for example, how alternating items or edited items appear through the ItemStyle, AlternateItemStyle, and EditItemStyle properties The DataGrid exposes the Style classes through these properties, applying . CLASS AND CONTROL STYLES 133 Figure 4-6. WebControl and top-level style properties The Style Property The ControlStyle property and top-level properties of WebControl do not expose the complete. to server controls. We also intro- duce a new method of building server controls that inherit from the WebControl class. The WebControl class provides an abstraction layer over the rendering process. font, color, and borders. Table 4-1 shows the properties that hang from the Style class and the CSS property that is rendered in conjunction with the property. CssClass is a string property that

Ngày đăng: 12/08/2014, 23:20

Từ khóa liên quan

Mục lục

  • Pro ASP.NET 3.5 Server Controls and AJAX Components

  • Contents at a Glance

  • Contents

  • About the Authors

  • About the Technical Reviewer

  • Acknowledgments

  • Introduction

    • Who This Book Is For

    • How This Book Is Structured

    • Prerequisites

    • Downloading the Code

    • Contacting the Authors

    • Server Control Basics

      • Source Code

      • The Heart and Soul of ASP.NET

      • A .NET Framework fiHelo, WorldflWeb Form

      • Control Properties

      • Control Methods

      • Control Events

      • The Web Page As a Control Tree

      • The Root Controls

        • The System.Web.UI Namespace

        • System.Web.UI.HtmlControls Namespace

          • An HTML Controls Demonstration

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan