How to create user define (new) event for user control in WPF ?one small example

前端 未结 2 972
遇见更好的自我
遇见更好的自我 2020-12-16 10:23

I have one UserControl in which I am using a Canvas, and in that Canvas one Rectangle. I want to create a click event for that user control (Canva

相关标签:
2条回答
  • 2020-12-16 11:07

    i find this easier for passing value to handler:

    public event Action<string> onUserCodeFetched;
    
    private void btnEnterClicked(object sender, RoutedEventArgs e)
            {
                onUserCodeFetched(PersonellCode.Text);
                PersonellCode.Text = "";
            }
    
    0 讨论(0)
  • 2020-12-16 11:22

    A brief example on how to expose an event from the UserControl that the main window can register:

    In your UserControl:

    1 . Add the following declaration:

    public event EventHandler UserControlClicked;
    

    2 . In your UserControl_Clicked event raise the event like this:

     private void UserControl_MouseDown(object sender, MouseButtonEventArgs e)
     {
            if (UserControlClicked != null)
            {
                UserControlClicked(this, EventArgs.Empty);
            }
      }
    

    In your MainWindow:

    Your usercontrol will now have a UserControlClicked event which you can register to:

    <local:UserControl1 x:Name="UC" UserControlClicked="UC_OnUserControlClicked" />
    
    0 讨论(0)
提交回复
热议问题