Click here to Skip to main content
15,886,077 members
Articles / Programming Languages / C#

Tweaked Events

Rate me:
Please Sign up or sign in to vote.
4.83/5 (12 votes)
18 Dec 2010MIT18 min read 34.8K   289   41  
Framework for customizing events. Comes with Weak Events and Synced Events
#define TWE

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using JpLabs.TweakedEvents;

namespace JpLabs.WeakEventDemo
{
	public partial class MyForm : Form, ICounter
	{
		public MyForm()
		{
			InitializeComponent();
		}
		
		#if !TWE
		
		public event EventHandler<CountEventArgs> IssueCount;
		
		#else
		
		private TweakedEvent<EventHandler<CountEventArgs>> issueCountEvent = new WeakEvent<EventHandler<CountEventArgs>>();
		
		public event EventHandler<CountEventArgs> IssueCount
		{
			//add    { issueCountEvent = issueCountEvent + value; }
			//remove { issueCountEvent -= value; }
			add { TweakedEvent.Add(ref issueCountEvent, value); }
			remove { TweakedEvent.Remove(ref issueCountEvent, value); }
		}
		
		#endif

		private void btnAdd_Click(object sender, EventArgs e)
		{
			lstItems.Items.Add(new IncrementerComponent(Guid.NewGuid().ToString(), this));
		}

		private void btnRemove_Click(object sender, EventArgs e)
		{
			var selected = lstItems.SelectedItem;
			
			if (selected != null) {
				lstItems.Items.Remove(selected);
			} else if (lstItems.Items.Count > 0) {
				lstItems.Items.RemoveAt(0);
			}
			
			GC.Collect();
		}

		private void btnIssueCount_Click(object sender, EventArgs e)
		{
			var evArgs = new CountEventArgs();
			
			OnIssueCount(evArgs);
			
			lblLastCount.Text = string.Format("{0} components", evArgs.Count);
		}

		private void OnIssueCount(CountEventArgs e)
		{
			#if !TWE
			
			var dlg = this.IssueCount;
			if (dlg != null) dlg(this, e);
			
			#else
			
			issueCountEvent.Raise(this, e);
			
			#endif
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Software Developer (Senior) ThoughtWorks
Brazil Brazil
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions