2013-01-16 43 views
-1

我跟着this的問題,並試圖構建我的解決方案。問題是'UserControlButtonClicked'顯示爲空!所以'UserControlButtonClicked(this,EventArgs.Empty)'在if內部,不運行,並且父頁面中的方法'addStepContent'永遠不會被調用。從UserController調用父頁面的方法

用戶控件「StepsBar」

public sealed partial class StepsBar : UserControl 
    { 

     public event EventHandler UserControlAddStepContent; 

     [...] 

    public StepsBar() 
    { 
     this.InitializeComponent(); 
        Image step_1 = new Image(); 

     ButtonInfo step_1Info = new ButtonInfo(); 
     step_1Info.Add((int)stepNumber.one, (int)stepStatus.normal); 
     step_1.Tag = step_1Info; 

     step_1.Source = setBackground((int)stepStatus.normal); 
     step_1.Tapped += stepTapped; 

     [...] 
    } 

public void stepTapped(Object sender, RoutedEventArgs e) 
    { 
     [...] 

     if (step != null) 
     { 

      [...] 

      firePageEvent(); 

     } 

    } 

    public void firePageEvent() 
    { 
     if (UserControlAddStepContent != null) 
     { 
      UserControlAddStepContent(this, EventArgs.Empty); 
     } 
    } 

父頁

public Violation() 
    { 

     this.InitializeComponent(); 

     StepsBar stepsBar = new StepsBar(); 

     stepsBar.UserControlAddStepContent += new EventHandler(addStepContent); 


    } 

    private void addStepContent(object sender, EventArgs e) 
    { 

     CheckBox check_1 = new CheckBox(); 
     check_1.Content = "Check me!"; 
     bodyStackPanel.Children.Add(check_1); 

    } 

回答

-1

已解決。問題出在父頁上。

StepsBar stepsBar = new StepsBar(); 

    stepsBar.UserControlAddStepContent += new EventHandler(addStepContent); 

StepsBar的遺感未添加到頁面中。 D'OH! 因此,這裏是我做了什麼:

stepsBar.UserControlAddStepContent += new EventHandler(addStepContent); 

和父頁面的XAML:

<local:StepsBar x:Name="stepsBar"/> 
-1

這是假設你想使用一個現有的委託,而不是讓你自己和你不傳遞任何由事件參數指定給父頁面。

在用戶控件的代碼隱藏(適應的必要的,如果不使用代碼隱藏或C#):

public partial class MyUserControl : System.Web.UI.UserControl 
    { 
     public event EventHandler UserControlButtonClicked; 


    private void OnUserControlButtonClick() 
    { 
     if (UserControlButtonClicked != null) 
     { 
      UserControlButtonClicked(this, EventArgs.Empty); 
     } 
    } 

    protected void TheButton_Click(object sender, EventArgs e) 
    { 
     // .... do stuff then fire off the event 
     OnUserControlButtonClick(); 
    } 

    // .... other code for the user control beyond this point 
} 

在頁面本身你訂閱事件像這樣的東西:

public partial class _Default : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     // hook up event handler for exposed user control event 
     MyUserControl.UserControlButtonClicked += new 
        EventHandler(MyUserControl_UserControlButtonClicked); 
    } 
    private void MyUserControl_UserControlButtonClicked(object sender, EventArgs e) 
    { 
     // ... do something when event is fired 
    } 

} 
+0

正如我在這個問題寫了,我用粘貼確切的例子,而是工作:UserControlButtonClicked'顯示爲空!所以'UserControlButtonClicked(this,EventArgs.Empty)'在if裏面,不會運行。 –

+0

我只提供了一個按預期工作的示例,並且可以訪問父頁上的方法。 –