Search code examples
wpfeventsuser-controls

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


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 (Canvas and Rectangle) which I then want to use in the main window.

The question is: I want to create a new click event for the UserControl. How to do it? Kindly show little example or the code.


Solution

  • 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" />