Usercontrol与不同的aspx,但相同的实现

时间:2011-07-25 15:28:53

标签: c# asp.net user-controls

我想区分用户控件的视觉方面,但使用相同的代码隐藏。 即我想在.ascx文件中使用两个usercontrol:

CodeBehind =“Uploader.ascx.cs”Inherits =“Comptech2.moduli.uploader.Uploader”

通过这种方式,我可以在不改变背后代码的情况下改变视觉方面。

由于 阿尔贝托

1 个答案:

答案 0 :(得分:2)

为您的usercontrol创建一个基类,最终的usercontrols(* .aspx文件)将派生自基类。

// base class with common functionality
public class MyUserControlBase : UserControl {
    // derived class will initialize this property
    public TextBox TextBox1 {get;set;}
    // derived class will initialize this property
    public Button Button1 {get;set;}

    /* some code of usercontrol */
}

/* ... elsewhere ... */
// final class with *.aspx file
public class MyUserControlA : MyUserControlBase {
    protected override OnInit(EventArgs e) {
        // "this.txtUrl" is generated from *.aspx file
        this.TextBox1 = this.txtUrl;
        // "this.btnSubmit" is generated from *.aspx file
        this.Button1 = this.btnSubmit;
    }
}

/* ... elsewhere ... */
// final class with *.aspx file
public class MyUserControlB : MyUserControlBase {
    protected override OnInit(EventArgs e) {
        // "this.txtTitle" is generated from *.aspx file
        this.TextBox1 = this.txtTitle;
        // "this.btnOk" is generated from *.aspx file
        this.Button1 = this.btnOk;
    }
}