如何在自定义Control中访问aspx页面的Public属性

时间:2017-05-23 05:53:37

标签: c# asp.net webforms

我已经创建了一个Custom控件并嵌入在aspx页面中。 现在我想访问自定义控件中aspx网页中的公共属性(例如:Test.ascx.cs) 我怎么能这样做?

TIA

1 个答案:

答案 0 :(得分:0)

将自定义控件的依赖项添加到外部是没有多大意义的。

创建一个包含您指定属性的接口:

public interface IMyPageInterface 
{
   string MyProperty {get;set;}
}

在您的网页上实现界面:

//your page code behind
public partial class WebForm1: System.Web.UI.Page,IMyPageInterface
{
    public string MyProperty 
    {
       get;
       set;
    }
}

您可以在自定义控件中将页面作为IMyPageInterface

IMyPageInterface myPage = this.Page as IMyPageInterface;
myPage.MyProp...

也可以定义IMyPageInterface类型的属性

public class MyControl :Control
{
    public IMyPageInterface MyPage
    {
        get
        {
            return this.Page as IMyPageInterface;
        }
    }
}