复合控制 - 用户控制 - 不同的方法
我看过这段代码来创建一个登录控件,我想我们可以使用 .ascx 文件来创建此控件,而不是编写这段代码。有人可以解释这两种方法的区别吗?谢谢。来源:http://www.joe-stevens.com/2010/04/16/creating-a-composite-server-control-with-asp-net/
[ToolboxData("<{0}:Login runat=server></{0}:Login>")]
public class Login : CompositeControl
{
private TextBox txtUsername = new TextBox();
private TextBox txtPassword = new TextBox();
private Button btnLogin = new Button();
protected override void CreateChildControls()
{
txtUsername.ID = "txtUsername";
txtPassword.ID = "txtPassword";
txtPassword.TextMode = TextBoxMode.Password;
btnLogin.ID = "btnLogin";
btnLogin.Text = "Login";
Controls.Add(txtUsername);
Controls.Add(txtPassword);
Controls.Add(btnLogin);
base.CreateChildControls();
}
}
I have seen this code to create a Login control, I guess instead of writing this code, we can use an .ascx file to create this control. Can someone explains the difference of these two approaches. thanks. source:http://www.joe-stevens.com/2010/04/16/creating-a-composite-server-control-with-asp-net/
[ToolboxData("<{0}:Login runat=server></{0}:Login>")]
public class Login : CompositeControl
{
private TextBox txtUsername = new TextBox();
private TextBox txtPassword = new TextBox();
private Button btnLogin = new Button();
protected override void CreateChildControls()
{
txtUsername.ID = "txtUsername";
txtPassword.ID = "txtPassword";
txtPassword.TextMode = TextBoxMode.Password;
btnLogin.ID = "btnLogin";
btnLogin.Text = "Login";
Controls.Add(txtUsername);
Controls.Add(txtPassword);
Controls.Add(btnLogin);
base.CreateChildControls();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
自定义服务器控件通常用于通用目的(超出您的应用程序),并且通常构建为可在多个应用程序之间共享的库。这些通常由 Telerik、Infragistics 等第三方供应商实施和销售。用户控件对于您的应用程序来说非常重要。您无法在多个应用程序之间共享它们(可能存在一些黑客行为,但通常不用于此目的)。它们不是作为库构建的,而是作为应用程序中包含的用户界面组件构建的。自定义服务器控件不提供构建它们的设计器支持,但用户控件具有设计器支持。因此,您的示例可以作为用户控件和自定义服务器控件来实现,具体取决于您对该控件的意图。话虽这么说,编写自定义服务器控件并非易事。这是 MS 的官方描述
http://msdn.microsoft.com/en-us/library/aa719735.aspx
Custom Server Controls typically serve a general purpose (beyond your application) and are typically built as a library to be shared across multiple applications. These are typically implemented and sold by third party vendors like Telerik, Infragistics, etc. User Controls are very centric to your application. You cannot share them across multiple applications (there may be some hacks, but generally not intended for that purpose). These are not built as libraries but as user interface components included in your application. Custom Server Controls don't provide designer support for building them but User Controls have designer support. So your example can be implemented both as a user control and custom server control depending upon what your intentions are for that control. That being said writing custom server controls is non-trivial. Here was a official description from MS
http://msdn.microsoft.com/en-us/library/aa719735.aspx