Add a Custom Event Handler to a User Control
Applies to Windows 8, Windows 8.1, Windows Phone 8.1 (XAML)
In your xaml.cs of your custom user control:
// Fire the event when a button clicks
private void Button_Click(object sender, RoutedEventArgs e)
{
MyCustomEventArgs arrrg = new MyCustomEventArgs();
arrrg.SomeMessage = "Hello world!";
arrrg.SomeValue = 3.1415926;
OnThingHappened(arrrrg);
}
// The thing that fires the event
protected virtual void OnThingHappened(MyCustomEventArgs e)
{
EventHandler<MyCustomEventArgs> handler = ThingHappened;
if (handler != null)
handler(this, e);
}
// The event
public event EventHandler<MyCustomEventArgs> ThingHappened;
Outside of the user control class (I usually put mine just below in the same file when I'm just hacking stuff together):
public class MyCustomEventArgs : EventArgs
{
public string SomeMessage { get; set; }
public double SomeValue { get; set; }
}
XAML:
<MyUserControl ThingHappened="Thing_EventHander" />
xaml.cs:
private void Thing_EventHander(object sender, MyCustomEventArgs e)
{
Debug.WriteLine(e.SomeMessage);
}