Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 904
Kiranaditya Avatar asked Nov 19 '12 05:11

Kiranaditya


People also ask

What is a user control in WPF?

User controls, in WPF represented by the UserControl class, is the concept of grouping markup and code into a reusable container, so that the same interface, with the same functionality, can be used in several different places and even across several applications.

How do I add user control to XAML?

The XamlFileBrowser Control Create a XAML application using Visual Studio 2008 and add a new item by right clicking on the project, select Add >> New Item from the menu and select User Control from the available templates.

What is the difference between user control and window in WPF?

A window is managed by the OS and is placed on the desktop. A UserControl is managed by wpf and is placed in a Window or in another UserControl. Applcations could be created by have a single Window and displaying lots of UserControls in that Window.


1 Answers

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" /> 
like image 51
Blachshma Avatar answered Sep 17 '22 15:09

Blachshma