2011-09-06 1 views
1

마스터 페이지와 aspx 페이지가 있습니다. 내부 사용자 컨트롤 (즉, 페이지 자체는 아니지만 다른 사용자 컨트롤 내부의 사용자 컨트롤)에서 전달되는 이벤트를 각각 듣고 싶습니다.마스터 페이지/aspx 페이지가 다른 usercontrol 내의 usercontrol에서 전달되는 이벤트를 수신 대기하는 방법

역할을 전환하는 것이 쉬울까요? 내부 컨트롤이 마스터 페이지임을 알리는 것을 의미합니까? 나는 이것을 보았다 : Help with c# event listening and usercontrols

그러나 문제는 더 복잡하다고 생각한다.

답변

0

컨트롤을 통해 반복되는 페이지 경로를 따라 가서 UserControl을 찾고 가장 간단하고 가장 직접적인 방법 인 EventHandler에 연결할 수 있습니다.

좀 더 많은 작업이 있지만, 특정 이벤트의 옵서버로 페이지를 등록하는 데 사용할 수있는 단일 이벤트 버스에 대한 아이디어가 마음에 든다. 그러면 UserControl이이를 통해 이벤트를 게시 할 수 있습니다. 즉, 체인의 양쪽 끝은 특정 게시자/구독자가 아니라 이벤트 (및 버스 또는 하나의 인터페이스)에 종속됩니다.

스레드 안전에주의하고 컨트롤이 이벤트 버스를 올바르게 공유하는지 확인해야합니다. 나는 ASP.NET WebForms MVP 프로젝트가 당신이 볼 수있는이 접근 방식을 취한다고 믿습니다.

0

다음과 같은 방법 사용해보십시오 :

당신의 UserControl에서 이벤트를 정의

public delegate void UserControl2Delegate(object sender, EventArgs e); 

public partial class UserControl2 : System.Web.UI.UserControl 
{ 
    public event UserControl2Delegate UserControl2Event; 

    //Button click to invoke the event 
    protected void Button_Click(object sender, EventArgs e) 
    { 
     if (UserControl2Event != null) 
     { 
      UserControl2Event(this, new EventArgs()); 
     } 
    } 
} 

가 Controls 컬렉션을 재귀 및 이벤트 처리기를 부착하여 페이지/마스터로드 방법에 UserControl을 찾기를

UserControl2 userControl2 = (UserControl2)FindControl(this, "UserControl2"); 
userControl2.UserControl2Event += new UserControl2Delegate(userControl2_UserControl2Event); 

... 

void userControl2_UserControl2Event(object sender, EventArgs e) 
{ 
    //Do something   
} 

... 

private Control FindControl(Control parent, string id) 
{ 
    foreach (Control child in parent.Controls) 
    { 
     string childId = string.Empty; 
     if (child.ID != null) 
     { 
      childId = child.ID; 
     } 

     if (childId.ToLower() == id.ToLower()) 
     { 
      return child; 
     } 
     else 
     { 
      if (child.HasControls()) 
      { 
       Control response = FindControl(child, id); 
       if (response != null) 
        return response; 
      } 
     } 
    } 

    return null; 
} 

희망 추신.

+0

시도해 보겠습니다. "delegate"와 "eventHandler"의 차이점은 무엇입니까? –

+0

대리자는 본질적으로 메서드에 대한 포인터입니다. 대리자 선언은 가리킬 수있는 메서드 서명을 정의합니다. 이 경우 메서드는 이벤트 처리기이며 UserControl2에서 이벤트가 호출 될 때 발생합니다. 다음 기사에서 내가 설명 할 수있는 것보다 더 잘 설명 할 때 이벤트 + 대표자를 너무 자세하게 설명하지 않겠다 : [이벤트 및 대표자 단순화] (http://www.codeproject.com/KB/cs/events.aspx) – jdavies

관련 문제