Properties with property changed event, part 3

A while ago, I talked about how to write basic events for changed properties, and about the INotifyPropertyChanged interface. There is a third way to manage events, which is especially useful when your class has many events, but you expect a very low number of them to be actually handled.

As discussed before, every EventHandler stored in your object takes up space, which is a bit of a waste if most of those will be null. But events allow you to implement the add and remove methods yourself, so you can choose where to store the EventHandler delegate.

One way to do that is through the System.ComponentModel.EventHandlerList class. System.ComponentModel.Component exposes an Events property of this type, which is used by all classes inheriting from Component, including all Windows Forms controls.

The following example inherits from System.Windows.Forms.TextBox, adding a CueBanner property (like the Internet Explorer 7 search box) and a CueBannerChanged event:

using System; 
using System.ComponentModel;
using System.Windows.Forms;

namespace U2U.Framework.Windows.Forms
{
/// <summary>
/// Textbox that displays a CueBanner when the Text is empty.
/// </summary>
public class CueBannerTextBox : TextBox
{
private string cueBanner = string.Empty;

/// <summary>
/// Gets or sets the prompt text to display when there is nothing in the Text property.
/// </summary>

[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
[Category("Appearance")]
[Description("The prompt text to display when there is nothing in the Text property.")]
[DefaultValue("")]
public string CueBanner
{
get { return cueBanner; }
set
{
if (value == null)
{
value = string.Empty;
}
if (value != cueBanner)
{
cueBanner = value;
NativeMethods.SendMessage(Handle, EM_SETCUEBANNER, IntPtr.Zero, cueBanner);
OnCueBannerChanged(EventArgs.Empty);
}
}
}

private const int EM_SETCUEBANNER = 0x1501;
private static readonly object EVENT_CUEBANNERCHANGED = new object();

/// <summary>
/// Occurs when the value of the <see cref="CueBanner"/> property has changed.
/// </summary>
[Category("Property Changed")]
[Description("Event raised when the value of the CueBanner property changed.")]
public event EventHandler CueBannerChanged
{
add { base.Events.AddHandler(EVENT_CUEBANNERCHANGED, value); }
remove { base.Events.RemoveHandler(EVENT_CUEBANNERCHANGED, value); }
}

/// <summary>
/// Raises the CueBannerChanged event.
/// </summary>
/// <param name="e">An <see cref="EventArgs"/> that contains the event data.</param>
protected virtual void OnCueBannerChanged(EventArgs e)
{
EventHandler handler = base.Events[EVENT_CUEBANNERCHANGED] as EventHandler;
if (handler != null)
{
handler(this, e);
}
}
}
}


You'll also need this:

using System; 
using System.Runtime.InteropServices;

namespace U2U.Framework.Windows.Forms
{
internal static class NativeMethods
{
[DllImport("user32", CharSet = CharSet.Unicode)]
internal static extern IntPtr SendMessage(IntPtr hWnd, int message, IntPtr wParam, string lParam);
}
}


Notice how the CueBannerChanged event provides an explicit implementation of the add and remove methods. The add method adds the delegate in the inherited Events collection, using a private static object as the key, and the remove method removes it from that same collection.

The OnCueBannerChanged method retrieves the delegate from the same collection, using the same key. Notice how this collection can store any type of delegate, not just EventHandlers, so we need to cast it back to EventHandler before we can use it.

Enjoy.

Technorati Tags: , , , , ,

Comments

March 11. 2009 04:58 AM

Hi,  Nice explanations ....  Do you know how to subscribe to all events, like in a propertyGrid? I.E. when a propertie of the managed control change, it is reflected in the grid display.  Thanks, Eclos

January 8. 2010 12:36 AM

onesies for newborns

Aw, this was a really quality post. In theory I'd like to write like this too - taking time and real effort to make a good article... but what can I say... I procrastinate alot and never seem to get something done.

onesies for newborns

January 8. 2010 09:56 PM

overcoming panic attacks

I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. In fact your creative writing abilities has inspired me to start my own BlogEngine blog now. Really the blogging is spreading its wings rapidly. Your write up is a fine example of it.

overcoming panic attacks

January 13. 2010 02:17 AM

Online Tutor

I thought it was going to be some boring old post, but it really compensated for my time. I will post a link to this page on my blog. I am sure my visitors will find that very useful.

Online Tutor

January 15. 2010 02:36 AM

jobs for food science

Me and my friend were arguing about an issue similar to this! Now I know that I was right. lol! Thanks for the information you post.

jobs for food science

January 15. 2010 09:52 AM

Credit Crunch

Keep 'em coming... you all do such a great job at such Concepts... can't tell you how much I, for one appreciate all you do!

Credit Crunch

January 18. 2010 09:28 PM

Ventrilo Hosting

Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with more information? It is extremely helpful for me.

Ventrilo Hosting

January 23. 2010 06:46 PM

dr britt borden md

I admire the valuable information you offer in your articles. I will bookmark your blog and have my children check up here often. I am quite sure they will learn lots of new stuff here than anybody else!

dr britt borden md

January 28. 2010 08:20 PM

Free Hip Hop Beats

Howdy, i read your blog occasionally and i own a similar one and i was just wondering if you get a lot of spam comments? If so how do you prevent it, any plugin or anything you can advise? I get so much lately it's driving me mad so any assistance is very much appreciated.

Free Hip Hop Beats

February 2. 2010 03:33 AM

levis watches

Aw, this was a really quality post. In theory I'd like to write like this too - taking time and real effort to make a good article... but what can I say... I procrastinate alot and never seem to get something done.

levis watches

February 3. 2010 03:57 PM

cash loans

The only way to find the limits of the possible is by going beyond them to the impossible.

cash loans

February 4. 2010 11:27 PM

no fax personal loans

You don't have to fear defeat if you believe it may reveal powers that you didn't know you possessed.

no fax personal loans

February 5. 2010 03:08 PM

meridian idaho homes for sale

Howdy, i read your blog occasionally and i own a similar one and i was just wondering if you get a lot of spam comments? If so how do you prevent it, any plugin or anything you can advise? I get so much lately it's driving me mad so any assistance is very much appreciated.

meridian idaho homes for sale

February 6. 2010 08:22 PM

how to tie a Windsor knot

Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon.

how to tie a Windsor knot

February 7. 2010 11:07 PM

swing trading

Great post! I am just starting out in community management/marketing media and trying to learn how to do it well - resources like this article are incredibly helpful. As our company is based in the US, it?s all a bit new to us. The example above is something that I worry about as well, how to show your own genuine enthusiasm and share the fact that your product is useful in that case.

swing trading

February 10. 2010 08:08 AM

toddler car seat

Just wanted to give you a shout from the valley of the sun, great information. Much appreciated.

toddler car seat

February 22. 2010 02:07 AM

Mother's Day 2010

Resources like the one you mentioned here will be very useful to me! I will post a link to this page on my blog. I am sure my visitors will find that very useful.

Mother's Day 2010

February 24. 2010 12:40 AM

make money online

I admit, I have not been on this webpage in a long time... however it was another joy to see It is such an important topic and ignored by so many, even professionals. I thank you to help making people more aware of possible issues.
Great stuff as usual...

make money online

February 24. 2010 04:27 AM

wealthy affiliate scam

Its really nice blog where i find such a good knowledge about property and properties change in it.I am really happy to see here.

wealthy affiliate scam

March 3. 2010 09:09 PM

North Caldwell NJ Plumbing

The blog was absolutely fantastic! Lots of great information and inspiration, both of which we all need!

North Caldwell NJ Plumbing

March 5. 2010 12:38 PM

boards

I was wondering what is up with that weird gravatar??? I know 5am is early and I'm not looking my best at that hour, but I hope I don't look like this! I might however make that face if I'm asked to do 100 pushups. lol

boards

March 11. 2010 12:31 AM

seo link building

Just wanted to give you a shout from the valley of the sun, great information. Much appreciated.

seo link building

March 12. 2010 02:12 AM

tutors

I am not much of a guy who thinks in so deeply about web design but I think your post had some valid points in it. Like designers are forced to design stuff within the limited code available and not go beyond it, their innovation is somewhat limited but still I think Web Design won't die! I agree that Amazon and other some big sites won't have a blog but now a days it's very important to have some sort of option available so people can quickly communicate their thoughts. I think Amazon if wants to shift it to that, they can get a customized CMS for themselves.

tutors

March 16. 2010 09:52 AM

emekli sandıgı

This is a really good read for me, Must admit that you are one of the best bloggers I ever saw.Thanks for posting this informative article.

emekli sandıgı

March 16. 2010 04:07 PM

SEO consultation

While this subject can be very touchy for most people, my opinion is that there has to be a middle or common ground that we all can find. I do appreciate that youve added relevant and intelligent commentary here though. Thank you!

SEO consultation

March 16. 2010 04:32 PM

arac sorgulama

I admire the valuable information you offer in your articles. I will bookmark your blog and have my children check up here often. I am quite sure they will learn lots of new stuff here than anybody else!

arac sorgulama

March 17. 2010 11:44 AM

cheap fashion jewelry

Resources like the one you mentioned here will be very useful to me! I will post a link to this page on my blog. I am sure my visitors will find that very useful.

cheap fashion jewelry

March 31. 2010 07:46 AM

KY Payday Loans

You can never plan the future by the past.

KY Payday Loans

March 31. 2010 07:47 AM

MD Payday Loans

Shoot for the moon. Even if you miss, you'll land among the stars.

MD Payday Loans

April 6. 2010 07:31 PM

hikaye

Thanks a lot for enjoying this beauty article with me. I am apreciating it very much! Looking forward to another great article. Good luck to the author! all the best!

hikaye

April 15. 2010 03:06 PM

kapadokya

Excellent post.I want to thank you for this informative read, I really appreciate sharing this great post. Keep up your work.

kapadokya

April 21. 2010 09:25 PM

plaka sorgulama

Thanks a lot for enjoying this beauty article with me. I am apreciating it very much! Looking forward to another great article. Good luck to the author! all the best!

plaka sorgulama

April 23. 2010 07:40 AM

rezzan kiraz

I just couldnt leave your website before saying that I really enjoyed the quality facts you provide to all your visitors. Would be back generally to check up on new stuff in you article!

rezzan kiraz

April 23. 2010 07:56 PM

fallar fal bakma

Thanks a lot for enjoying this beauty article with me. I am apreciating it very much! Looking forward to another great article. Good luck to the author! all the best!

fallar fal bakma

April 26. 2010 08:54 PM

trafik ceza sorgulama

Hello,I love reading through your blog, I wanted to leave a little comment to support you and wish you a good continuation. Wishing you the best of luck for all your blogging efforts.

trafik ceza sorgulama

April 28. 2010 08:48 AM

thy bilet fiyatları

Thank you for another great article. Where else could anyone get that kind of information in such a perfect way of writing? I have a presentation next week, and I am on the look for such information

thy bilet fiyatları

May 4. 2010 09:41 AM

bağkur borc sorgulama

This is a really good read for me, Must admit that you are one of the best bloggers I ever saw.Thanks for posting this informative article.

bağkur borc sorgulama

May 5. 2010 09:26 PM

sgk

I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post

sgk

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading