c# - c# 中的派生用户控件会覆盖其父级的 html 是否可以不这样做?

标签 c# asp.net user-controls

我正在做一个项目,有一组动态加载的用户控件,想想一个带有一堆小部件( block )的门户页面,它们都是一个用户控件。 它们有某些共同点,所以我让它们都派生自 masterBlock 用户控件

现在有没有办法也有一些共同的输出(在 .ascx 中)文件? 我放在 masterBlock 的 ascx 中的任何内容都不会被派生 block 渲染或覆盖。

我想知道是否有人有任何提示可以让它工作。

最佳答案

*.ascx 文件不能导出(也许用一些“魔法”可以)。派生只能是类,因此您可以创建一个 MyUserControlBase 类,它可以创建一些公共(public)控件/输出并通过 protected /公共(public)属性将其提供给可以公共(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 );
    }
}

关于c# - c# 中的派生用户控件会覆盖其父级的 html 是否可以不这样做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1366780/

相关文章:

c# - 名称为 'Id' 的成员已存在于 `Model` 上。使用 JsonPropertyAttribute 指定另一个名称

c# - 如何使用 JsonProperty 获取嵌套属性

c# - Web API 2 中的 ExceptionFilter 与 ExceptionLogger 与 ExceptionHandler

asp.net - 其他 Web 技术中是否有与 ASP.NET ViewState 等效的东西?

winforms - 在 3.5 中重新编译 .NET 2.0 UserControl 库?

c# - 构造类型、有界类型和无界类型的含义?

c# - 如何检查FTP目录是否存在

asp.net - 将 Visual Studio 2010 中的 ASP.NET 网站连接到 SQL Server 2008

c# - WPF 用户控件的加载事件多次触发

c# - 如何在用户控件中的两个控件之间绘制直线?