简体   繁体   中英

Cast an object in a control to a class in its parent control

I'm trying to access a member of a parent control of my current control.

Here is the parent:

public partial class Controls_MyPanel : System.Web.UI.UserControl
{
    private String _strSubTitle = String.Empty;

    public String SubTitle
    {
        get { return _strSubTitle; }
        set
        {
            _strSubTitle = value;
            lblSubTitle.Text = _strSubTitle;
        }
    }
}

Here is the child control:

public partial class Controls_MyChild : System.Web.UI.UserControl
{
    function ChangeSubTitle
    {
        ((Controls_MyPanel)Parent.Parent).SubTitle = "Foo";
    }
}

I can't figure out how to get the defintion of Controls_MyPanel into Controls_MyChild. I can't use using because I don't have a namespace. I tried adding something like:

<%@ Register src="MyPanel.ascx" tagname="MyPanel" tagprefix="uc1" %>

to the markup for MyChild , but of course that's circular, since MyChild is already registered on MyPanel .

This will happen if you created a website project (with ASP.net) instead of a pure ASP.net application.

File->New->Web Sites...

instead of

File->New->Project...->Visual C#->Web->ASP.NET Web Application

In Web Site project, the code behind file is compiled dynamically when page is loaded. They're isolated so you cannot reference the name of the class unless you Register in the aspx/ascx file, which in your case would create circular dependency.

To solve the problem, if you don't want to change project type, you can use interface.

  1. Right click the web site project, Add->Add New Item...

  2. Select "Class". Visual Studio will prompt you if you want to place the file in App_Code. Yes.

  3. In the generated file, change public class ClassName to public interface ISomeInterface . Then define a property like String SubTitle {get; set;} String SubTitle {get; set;}

  4. Implement the interface in your parent control.

  5. In your child control, cast the Parent.Parent to ISomeInterface

Then you can access the SubTitle property via the ISomeInterface interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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