技术开发 频道

asp.net控件设计时支持(4)

【IT168 技术文档】首先还是示例代码下载
       这次让我们来看下控件可编辑设计区域的设计时支持.

一.单区域编辑

1.介绍

在内置控件中,典型的则是Panel控件,如下图


其在设计时提供了一个编辑区域,可方便的编辑控件内部文本,并提供了一个标题属性,此设计时呈现效果并非呈现以后的效果.另外除Panel控件外,MultiView控件也提供相似的设计时支持.下面我们看一下类图



ContainerControlDesigner 提供单个带框区域来表示控件,注意是单个,你只需要关注以上两个属性和一个方法既可,最终的封装实现还是调用GetDesignTimeHtml 方法的,以下为属性简单说明

FrameCaption  设置时显示的标题

FrameStyle  设置时显示的标题样式


2.实现

2.1
自定义一个继承ContainerControlDesigner的类,并重写相关属性

    public class SimpleContainerControlDesigner : ContainerControlDesigner
    
{
        
private Style _style = null;

        
//设计时标题
        public override string FrameCaption
        
{
            
get
            
{
                
return "我的测试控件";
            }

        }


        
//设计时标题样式
        public override Style FrameStyle
        
{
            
get
            
{
                
if (_style == null)
                
{
                    _style 
= new Style();
                    _style.Font.Name 
= "Verdana";
                    _style.Font.Size 
= new FontUnit(FontSize.XLarge);
                    _style.BackColor 
= Color.LavenderBlush;
                    _style.ForeColor 
= Color.DarkBlue;
                }


                
return _style;
            }

        }

    }


2.2 自定义控件,并与控件相关联,该控件只提供了一个背景图片的属性

    [
        Designer(
typeof(SimpleContainerControlDesigner)),
        ParseChildren(
false)
    ]
    
public class SimpleContainerControl : WebControl
    
{
        
public string BackgroundImage
        
{
            
get return ViewState["BackgroundImage"!= null ? (string)ViewState["BackgroundImage"] : ""; }
            
set { ViewState["BackgroundImage"= value; }
        }


        
protected override void AddAttributesToRender(HtmlTextWriter writer)
        
{
            
base.AddAttributesToRender(writer);
            writer.AddStyleAttribute(HtmlTextWriterStyle.BackgroundImage, BackgroundImage);

        }

    }



好了,大功告成,可以看下效果了



2.3 设计时区域样式

还没完呢,为什么我故意设置一个BackgroundImage属性呢,现在我们设置BackgroundImage属性,当设置好以后(请一定设置此属性),你有没发现此控件区域内并没有出现背景图片.还不如不加自定义的设计时支持呢?

原因: 区域编辑区域样式的设计时的每个属性都是由ContainerControlDesigner帮你写好的,里面包括WebControl公有属性,这些不需要你重写,但当你自定义属性需要呈现,而你又想完美的在设计时看到效果时,则你必须重写AddDesignTimeCssAttributes方法了,如BackgroundImage属性,Panel控件也有背景图片这个属性,其设计时支持也是这么做的.实现方法如下

        //添加设计时样式属性
        protected override void AddDesignTimeCssAttributes(System.Collections.IDictionary styleAttributes)
        
{
            
base.AddDesignTimeCssAttributes(styleAttributes);
            SimpleContainerControl control 
= base.ViewControl as SimpleContainerControl;
            
string BackgroundImage = control.BackgroundImage;
            
if (BackgroundImage.Trim().Length > 0)
            
{
                styleAttributes[
"background-image"= "url(" + BackgroundImage + ")";
            }

        }


好了再测试下,效果出来了.以上我认为是理解的重点,其他倒没什么,大家多修改即可理解.

0
相关文章