开发者

How can I call aspx content page methods from usercontrol? ASP.NET, C#

How can I c开发者_如何学Pythonall aspx content page methods from usercontrol?


Probably the cleanest solution is to extract an interface containing the methods that must be called from the UserControl, and then pass the interface from the page to the control, e.g:

public interface ISomeService
{
  void Method1();
  bool Method2();
}

public class MyContentPage : Page, ISomeService
{
  void Method1() { ... }
  bool Method2() { ... }

  override OnLoad(...)
  {
    TheUserControl.SetService(this as ISomeService);
  }
}

public class MyUserControl : UserControl
{
  public void SetService(ISomeService service)
  {
    _service = service;
  }

  private void SomeOtherMethod()
  {
    _service.Method1();
  }
}

Another variation would be to simply require the page containing the user control to implement the required interface. This makes the SetService() method unneeded:

public class MyUserControl : UserControl
{
  private void SomeOtherMethod()
  {
    // page must implement ISomeService, throws an exception otherwise
    (Page as ISomeService).Method1();
  }
}


You are most likely creating a very bad design at this point. If it needs to have access to its parent, it probably shouldn't be a UserControl. Are you sure you can't just add an event handler to your usercontrol that the parent page calls on certain events?

That said, your UserControl will have the .Page property you can cast to get your parent page. Again, it's probably a very bad idea and you should revisit your design.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜