如何在用户控件中访问.aspx的属性?

时间:2012-09-25 04:58:24

标签: c# asp.net

我有一个.aspx页面,其中有一个属性。现在我创建一个用户控件并将其放在页面上。现在我如何在usercontrol后面的代码中访问该属性。

2 个答案:

答案 0 :(得分:2)

如果用户控件需要访问父页面上的某些内容,那么该用户控件可能应该将其作为自己的属性包含在内,该属性可以从父级设置。理想情况下,用户控件应独立于页面上的任何父上下文或其他用户控件,否则它们实际上不是可重用的。它们需要在其所暴露的属性中自包含且可配置。

答案 1 :(得分:2)

最好的方法是在UserControl中公开一个公共属性,并从ASPX页面分配该属性:

按代码:

var uc = this.myUserControl as MyCuserControlType;

uc.CustomUserControlProperty = this.MyPageProperty;

以声明

<uc:MyUserControlType1 runat="server= ID="myUserControl" CustomUserControlProperty="<%# this.MyPageProperty %>" />

注意:如果要使用声明性标记,则需要在代码中调用this.DataBind();来强制绑定

编辑1

如果您想要执行相反的操作(将控件中的值传递给页面以响应事件),您可以在用户控件中声明自己的自定义事件,并在需要时触发它。

示例:

用户控制代码*

public event Action<string> MyCustomEvent = delegate{};

....
// somewhere in your code
this.MyCustomEvent("some vlaue to pass to the page");

页面标记

<uc:MyUserControl1 runat="server" onMyCustomEvent="handleCustomEvent" />

页面代码

public void handleCustomEvent(string value)
{
    // here on the page handle the value passed from the user control
    this.myLabel.Text = value;
    // which prints: "some vlaue to pass to the page"
}
相关问题