在c#中派生的usercontrol从其父级覆盖html是否有可能不这样做?

时间:2009-09-02 09:53:37

标签: c# asp.net user-controls

我正在开发一个项目,其中有一组用户控件,动态加载,想一下带有一堆小部件(块)的门户页面,所有这些都是用户控件。 他们有一些共同的东西,所以我把它们都来自masterBlock用户控件

现在是否有一种方法可以同时拥有一些输出(在.ascx文件中)? 我放在masterBlock的ascx中的任何内容都不会被派生块渲染或覆盖。

我想知道是否有人有任何提示要让它发挥作用。

2 个答案:

答案 0 :(得分:3)

无法导出* .ascx文件(也许有一些“魔术”可以)。 Derived可以只是类,你可以创建一个MyUserControlBase类,它可以创建一些常见的控件/输出,并通过protected / public属性提供给派生类(例如MyWeatherUserControl),它可以进行常见的控件/输出修改。

示例代码:

public class MyUserControlBase : UserControl {
    private Panel mainPanel;
    protected Panel MainPanel {
        get { return this.mainPanel; }
    }

    public MyUserControlBase() {
        this.mainPanel = new Panel();
        this.Controls.Add( this.mainPanel );
        this.CreateMainPanelContent();
    }

    protected virtual void CreateMainPanelContent() {
        // create default content
        Label lblInfo = new Label();
        lblInfo.Text = "This is common user control.";
        this.MainPanel.Controls.Add( lblInfo );
    }
}

public class MyWeatherUserControl : MyUserControlBase {
    protected override void CreateMainPanelContent() {
        // the base method is not called,
        // because I want create custom content

        Image imgInfo = new Image();
        imgInfo.ImageUrl = "http://some_weather_providing_server.com/current_weather_in_new_york.gif";
        this.MainPanel.Controls.Add ( imgInfo );
    }
}

public class MyExtendedWeatherUserControl : MyWeatherUserControl {
    protected override void CreateMainPanelContent() {
        // the base method is called,
        // because I want only extend content
        base.CoreateMainPanelContent();

        HyperLink lnkSomewhere = new Hyperlink();
        lnkSomewhere.NavigationUrl = "http://somewhere.com";
        this.MainPanel.Controls.Add ( lnkSomewhere );
    }
}

答案 1 :(得分:1)

您可以覆盖基类中的Render方法,为您提供自定义呈现,然后子类可以使用它。