I've created a custom UserControl
, it's a button with a grid inside it.
From the Page that contains it, MainPage.xaml
, I need to bind a Click
event to the UserControl, and the function for the EventHandler
must be written outside, in the MainPage (not inside the UserControl).
So, reading through this question, I've created an Event and a EventHandler function that triggers the event. These are inside the UserControl. This are the classes
UserControl.xaml.cs
public class MyButton : UserControl
{
public event RoutedEventHandler ButtonClicked;
private void ButtonClickedHandler()
{
//Null check makes sure the main page is attached to the event
if (this.ButtonClicked != null)
this.ButtonClicked(this, new RoutedEventArgs());
Debug.WriteLine("ButtonClickedHandler");
}
}
MainPage.xaml.cs
private void MyButton_Click(object sender, RoutedEventArgs e)
{
Debug.WriteLine("MyButton_Click");
}
private void MyButton_Loaded(object sender, RoutedEventArgs e)
{
(sender as MyButton).ButtonClicked += MyButton_Click;
}
As you can see, I've placed a couple of Debug.WriteLine
, but they don't get triggered, and I don't know what I'm doing wrong.