How to build ImageButton Control Adapter (or more general, how to build a simple control adapter)?

后端 未结 1 1491
Happy的楠姐
Happy的楠姐 2021-01-07 13:28

My inspiration for this question was my discovery of the very annoying default style (border-width: 0px;) on the ImageButton web control. The simple solution is

相关标签:
1条回答
  • 2021-01-07 14:04

    There are two ways to do this. Both will require writing up a custom Control Adapter. Either you can set the actual value in code, or you can just not include the value at all and then use CSS to set your value. Here's the code you'll need to do this.

    namespace TestApp
    {
        using System.IO;
        using System.Web.UI;
        using System.Web.UI.Adapters;
    
        public class ImageAdapter : ControlAdapter
        {
            protected override void Render(HtmlTextWriter writer)
            {
                base.Render(new RewriteImageHtmlTextWriter(writer));
            }
    
            public class RewriteImageHtmlTextWriter : HtmlTextWriter
            {
                public RewriteImageHtmlTextWriter(TextWriter writer)
                    : base(writer)
                {
                    InnerWriter = writer;
                }
    
                public RewriteImageHtmlTextWriter(HtmlTextWriter writer)
                    : base(writer)
                {
                    InnerWriter = writer.InnerWriter;
                }
    
                public override void AddAttribute(HtmlTextWriterAttribute key, string value, bool fEncode)
                {
                    if (key == HtmlTextWriterAttribute.Border)
                    {
                        // change the value
                        //value = "2";
    
                        // -or-
    
                        // don't include the value
                        //return;
                    }
    
                    base.AddAttribute(key, value, fEncode);
                }
    
                public override void AddStyleAttribute(HtmlTextWriterStyle key, string value)
                {
                    if (key == HtmlTextWriterStyle.BorderWidth)
                    {
                        // change the value
                        //value = "2px";
    
                        // -or-
    
                        // don't include the value
                        //return;
                    }
    
                    base.AddStyleAttribute(key, value);
                }
            }
        }
    }
    

    Then you'll need to add an entry into one of your browser files like this

    <browsers>
      <browser refID="Default">
        <controlAdapters>
          <adapter controlType="System.Web.UI.WebControls.Image" adapterType="TestApp.ImageAdapter, TestApp" />
        </controlAdapters>
      </browser>
    </browsers>
    
    0 讨论(0)
提交回复
热议问题