我正在做一个项目,有一组动态加载的用户控件,想想一个带有一堆小部件( 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/