我根据 this post 向页面动态添加自定义用户控件.
但是,我需要在用户控件上设置一个属性,因为我将它添加到页面。我怎么做?
代码片段会很好 :)
详细信息:
我有一个带有公共(public)字段的自定义用户控件(属性...例如 public int someId;)
当我向页面添加一个 UserControl 时,它的类型是 UserControl。我是否只是将其转换为 MyCustomUCType 并在转换控件上设置一个属性?
附注看来我终于回答了我自己的问题。
最佳答案
啊,我在你添加额外的说明之前回答了。简短的回答是,是的,只需将其转换为您的自定义类型即可。
我会把剩下的答案留在这里以供引用,尽管您似乎不需要它。
借用其他问题中的代码,并假设您的所有用户控件都可以从同一个基类继承,您可以这样做。
创建一个新类作为基础控件:
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);
关于c# - 在动态添加的 UserControl 上设置属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/508826/