Create event based component in C#

This post is about how to create event based component in C# for Windows Phone. Assuming that we have XAML class that interact with data model component, we’re using event to pass the data around.

In model class, create delegate and event property. Delegate is property that define the signature of callback, and event is property that other class can hook their callback to.

If you want to pass additional parameters in event handler, declare a new event argument class that extend EventArgs and assign the values when raising the event

public class DataLoadedEventArgs : EventArgs
{
	public int TotalRows { get; set; }
}

public class DataSource
{
	public delegate void DataLoadedEventHandler(object sender, DataLoadedEventArgs e);
	public delegate void DataErrorEventHandler(object sender, EventArgs e);

	public event DataLoadedEventHandler DataLoaded;
	public event DataErrorEventHandler DataError;

	public void GetDataFromServer()
	{
		// code for getting data

		// this is how to raise the event
		if (DataLoaded != null)
		{
			DataLoaded(this, new DataLoadedEventArgs()
			{
				TotalRows = 20
			});
		}

		// if has error, raise another event
		if (DataError != null)
		{
			DataError(this, new EventArgs());
		}
	}
}

Then in XAML class attach the callback to listen for the event raised from the model class, and make sure to detach the event when not used anymore.

public partial class MainPage : PhoneApplicationPage
{
	private DataSource dataSource;

	private void MainPage_Loaded(object sender, RoutedEventArgs e)
	{
		dataSource = new DataSource();
		dataSource.DataLoaded += dataSource_DataLoaded;
		dataSource.DataError += dataSource_DataError;
	}

	private void MainPage_Unloaded(object sender, RoutedEventArgs e)
	{
		dataSource.DataLoaded -= dataSource_DataLoaded;
		dataSource.DataError -= dataSource_DataError;
	}

	private void dataSource_DataLoaded(object sender, DataLoadedEventArgs e)
	{
		// use e.TotalRows
	}

	private void dataSource_DataError(object sender, EventArgs e)
	{
		// ...
	}
}
Share this...
Share on FacebookTweet about this on TwitterShare on Google+Share on LinkedInPin on Pinterest

Leave a Reply

Your email address will not be published. Required fields are marked *