繁体   English   中英

在动态添加的UserControl上设置属性

[英]Set properties on dynamically added UserControl

我正在根据这篇文章动态地向页面添加自定义用户控件。

但是,我需要在用户控件上设置属性,因为我将其添加到页面。 我怎么做?

代码片段会很好:)

细节:

我有一个带有公共字段的自定义用户控件(属性...例如public int someId;)

当我向页面添加UserControl时,它的类型是UserControl。 我只是将其转换为MyCustomUCType并在转换控件上设置属性吗?

ps看起来我毕竟回答了我自己的问题。

啊,我在你补充额外澄清之前回答了。 简短的回答是,是的,只需将其作为自定义类型。

我将把剩下的答案留在这里作为参考,虽然看起来你不需要它。


借用其他问题中的代码,并假设所有用户控件都可以从同一个基类继承,您可以这样做。

创建一个新类作为基本控件:

public class MyBaseControl : System.Web.UI.UserControl
{
    public string MyProperty 
    {
        get { return ViewState["MyProp"] as string; }
        set { ViewState["MyProp"] = value; }
    }
}

然后更新您的用户控件以继承您的基类而不是UserControl:

public partial class SampleControl2 : MyBaseControl
{
    ....

然后,在加载控件的位置,更改:

UserControl uc = (UserControl)LoadControl(controlPath);
PlaceHolder1.Controls.Add(uc);

至:

MyBaseControl uc = (MyBaseControl)LoadControl(controlPath);
uc.MyProperty = "foo";
PlaceHolder1.Controls.Add(uc);

“当我向页面添加UserControl时,它的类型是UserControl。我只是将它转换为MyCustomUCType并在转换控件上设置属性吗?”

这就是我要做的。 如果您实际使用的是加载不同控件的示例代码,我也会使用if(x是ControlType)。

 if(x is Label) { Label l = x as Label; l.Text = "Batman!"; } else //... 

编辑 :现在它兼容2.0

是的,您只需将控件转换为正确的类型。 EX:

((MyControl)control).MyProperty = "blah";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM