【问题标题】:How to create and use a Generic Web Form User Control in ASP.NET?如何在 ASP.NET 中创建和使用通用 Web 窗体用户控件?
【发布时间】:2014-09-22 15:40:52
【问题描述】:

我使用 C# 创建了一个 Web 窗体用户控件。 我已更改用户控件的 .cs 文件(代码和设计器)以允许任何类型。

public partial class MyGenericControl<T> : System.Web.UI.UserControl
{
}

现在我正在尝试在像 thi 这样的 ASP.NET 表单中使用它

<uc1:MyGenericControl runat="server" id="MyGenericControl1"  />

但我不知道如何将我需要的类型发送给控件。

感谢您对此问题的任何建议或帮助。

【问题讨论】:

标签: c# asp.net webforms web-user-controls


【解决方案1】:

我会将我的回复放在评论中,因为我还没有答案,但我没有 50 个代表,所以我无法发表评论。

这是处理用户控件的一种非常有趣的方式。 我的问题是,你想用这个来完成什么?我们需要知道,因为您的解决方案可能不涉及接受任何类型的用户控件 - 就像 Stilgar 所说的那样。

您可以使用枚举器/属性组合来完成此操作。这是我想出的:

<uc1:MyGenericControl runat="server" id="MyGenericControl1" myControlType="DropDownList"  />

public partial class MyGenericControl<T> : System.Web.UI.UserControl
{
    public enum ucType : ushort
    {
        DropDownList = 1,
        TextBox,
        Button,
        Etc
    }

    private ucType _controlType;

    public ucType myControlType
    {
        get{return _controlType;}
        set{ T = value; } /* Somehow set T to the value set in ASP.  
    In this example, value would be "1" so it would throw an error, but you get the idea. */
    }
}

这比完整的答案更具启发性和发人深省,因为我不知道是否可以动态设置类类型(尤其是您当前正在使用的类类型)。有一个Convert.ChangeType 方法,但我认为这在这里行不通。

【讨论】:

  • 一个例子:硬输入通用事件而不是使用对象。 DropDownList怎么样?
猜你喜欢
  • 2017-06-07
  • 1970-01-01
  • 1970-01-01
  • 2011-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-08
  • 2019-08-09
相关资源
最近更新 更多