简体   繁体   English

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

[英]Set properties on dynamically added UserControl

I'm dynamically adding a custom user control to the page as per this post . 我正在根据这篇文章动态地向页面添加自定义用户控件。

However, i need to set a property on the user control as i add it to the page. 但是,我需要在用户控件上设置属性,因为我将其添加到页面。 How do I do that? 我怎么做?

Code snippet would be nice :) 代码片段会很好:)

Details: 细节:

I have a custom user control with a public field (property ... eg public int someId;) 我有一个带有公共字段的自定义用户控件(属性...例如public int someId;)

As I add a UserControl to a page, its type is UserControl. 当我向页面添加UserControl时,它的类型是UserControl。 Do i just cast it into MyCustomUCType and set a property on a cast control? 我只是将其转换为MyCustomUCType并在转换控件上设置属性吗?

ps looks like I've answered my own question after all. ps看起来我毕竟回答了我自己的问题。

Ah, I answered before you added the additional clarification. 啊,我在你补充额外澄清之前回答了。 The short answer is, yes, just cast it as your custom type. 简短的回答是,是的,只需将其作为自定义类型。

I'll leave the rest of my answer here for reference, though it doesn't appear you'll need it. 我将把剩下的答案留在这里作为参考,虽然看起来你不需要它。


Borrowing from the code in the other question, and assuming that all your User Controls can be made to inherit from the same base class, you could do this. 借用其他问题中的代码,并假设所有用户控件都可以从同一个基类继承,您可以这样做。

Create a new class to act as the base control: 创建一个新类作为基本控件:

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

Then update your user controls to inherit from your base class instead of UserControl: 然后更新您的用户控件以继承您的基类而不是UserControl:

public partial class SampleControl2 : MyBaseControl
{
    ....

Then, in the place where you load the controls, change this: 然后,在加载控件的位置,更改:

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

to: 至:

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

"As I add a UserControl to a page, its type is UserControl. Do i just cast it into MyCustomUCType and set a property on a cast control?" “当我向页面添加UserControl时,它的类型是UserControl。我只是将它转换为MyCustomUCType并在转换控件上设置属性吗?”

That's what I'd do. 这就是我要做的。 If you're actually using the example code where it loads different controls, I'd use an if(x is ControlType) as well. 如果您实际使用的是加载不同控件的示例代码,我也会使用if(x是ControlType)。

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

Edit : Now it's 2.0 compatible 编辑 :现在它兼容2.0

Yes, you just cast the control to the proper type. 是的,您只需将控件转换为正确的类型。 EX: EX:

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

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

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