Thursday, 2 August 2012

Post/Email-3: Events in .NET

Today, a friend of mine asked a question on facebook:
Any body knows why wouldn't the selectionChanged event be fired?
I'm trying to change the text of a textBlock once I scroll to the next item in a pivot page
When I came into the scene, so to speak, another person had supplied the fix for the issue like so:
hmm in xaml u have to call your function SelectionChanged="thisPivot_SelectionChanged" and your textblock gets changed...

Then I started talking to my friend, and here’s how our conversation went:

So, you fixed the issue!

I had to call the event in the xaml code too.
I didn't know about that

"call the event in xaml"?
what do you mean by that?

hmmm, yes
this line was missing: SelectionChanged="thisPivot_SelectionChanged"

you can't "call an event from xaml"!
here you "wire up" the event "SelectionChanged" to the event handler "thisPivot_SelectionChanged"
and you can do this from code or from xaml

"wire up"
that's new for me!

what did you do before this?

just defined the handler

ah, ok. and you just expected it to magically know when to fire (or rather when to be called)

yes yes :P

would you like me to give you a little explanation about events in .NET?

yeah, of course!

ok, so could you first tell me what do YOU know about events in .NET?

I know the concept
events are fired along the application
handlers must be defined to handle a specific event we need to handle to achieve some task in our app

ok, that's good

Now, here’s my simple overview on events in .NET:

Events, as their name suggests, are a mechanism in .NET that allows for an object to inform (notify) of something that happened to it (or in it) to a subscribing party (some other object that "declares an interest" in such a "thing"). An example of this is a "Pivot" object that has a "SelectionChanged" event, which means that it can notify subscribing objects when the selected pivot item changes.
this is allowed in a "loosely coupled" manner, meaning that although the subscriber has to know on which object it is subscribing, but the object that defines and fires the event doesn't have to know who is "listening" to the event

Moreover, the subscriber doesn't have to "wait" for the event. It just declares that it is interested in it, by providing an "event handler" (and in this case we say that it is "listening" to the event). When an event gets fired, all listening objects are notified, and their "event handlers" are called.

Each event has a corresponding "signature" that its handlers have to follow. A SelectionChanged event can be declared like so:
public event EventHandler<SelectionChangedEventArgs> SelectionChanged;
which means that any handler for this event has to have the following signature:
void Event_Handler_Name(object sender, SelectionChangedEventArgs args)
So, we have a couple of parameters:
a “sender” object, which would be the object that fired the event;
and an “event argument”, which is an object that generally derives from "EventArgs”, and is used to send relevant information about the event to the subscribing objects.
the syntax to subscribe to an event is like so:
(e.g. pivot.SelectionChanged+=thisPivot_SelectionChanged;)
it's what happens when you say Event="EventHandler" in xaml
At this point, my friend asked:
where to write it in the code?
in the constructor?

yeah, you can put it in the constructor if you want to make it available since the creation of the object, but you can do it inside any method you want

let's say that you don't want to start subscribing to the event only if the user clicks a certain button. in that case, you put it inside the event handler of the button click event (subscribing to an event, in the event handler of another event. not confusing at all  )
now, to "fire" an event, the object that defines it does something like this:
   handler(this, new SelectionChangedEventArgs{SelectedItem=selected});
so you notice a couple of things here.
first, the event is "copied" to a variable. This is done so that you don't get weird behavior if some object subscribes to the event while it's being fired. don't worry too much about this part
second, this copy (called handler in my code), is checked to see if there are any objects listening to the event (in which case the variable would be different than null)
then, the event is "fired", by calling handler and passing to it the "sender" of the event (in our case we put "this" meaning that it's the current object, which is logical), and the “event args” parameter which contains information about the event (in the case of a SelectionChanged for example, it can be the "Selected Item")

so, to recapitulate, an object defines an event (and gives it a corresponding event handler signature), interested objects listen to that event by declaring an event handler with the specified signature, which gets called when the event is fired
simple as that


  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru Dot Net Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
    or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.

  2. And therefore to gmail account without phone number you have to verify your account with different phone numbers which are quite a problematic situation

  3. AWS Training in Bangalore - Live Online & Classroom
    myTectra Amazon Web Services (AWS) certification training helps you to gain real time hands on experience on AWS. myTectra offers AWS training in Bangalore using classroom and AWS Online Training globally. AWS Training at myTectra delivered by the experienced professional who has atleast 4 years of relavent AWS experince and overall 8-15 years of IT experience. myTectra Offers AWS Training since 2013 and retained the positions of Top AWS Training Company in Bangalore and India.

    IOT Training in Bangalore - Live Online & Classroom
    IOT Training course observes iot as the platform for networking of different devices on the internet and their inter related communication. Reading data through the sensors and processing it with applications sitting in the cloud and thereafter passing the processed data to generate different kind of output is the motive of the complete curricula. Students are made to understand the type of input devices and communications among the devices in a wireless media.

  4. This comment has been removed by the author.

  5. Looking back at 1971, we know that Intel's introduction of the microprocessor marked the beginning of a new era. But in that year, this meant little to people watching Mary Tyler Moore and The Partridge Family, or listening to Tony Orlando & Dawn and Janis Joplin.TechRolet

  6. The development of high technology including computer technology's Internet and the phone has vanquished correspondence obstructions and conquer any hindrance between individuals everywhere throughout the under

  7. Interesting post. I Have Been wondering about this issue. so thanks for posting. Pretty cool post.It 's really very nice and Useful post.Thanks

  8. I am come here first time, i find the perfect article. Thanks for sharing interesting and informative post. visit site

  9. I found so many interesting stuff in your blog especially its discussion. Really its great article. Keep it up. vpn reviews

  10.  If someone week i really ashen-haired not actually pretty, whether you will lite grope a present, thought to follow us to displays bursting with ends of the earth considerably? Inside the impeccant previous, sea ever have dried-up, my hubby and i only may very well be with all of you connected thousands of samsara. privacyonline

  11. This comment has been removed by the author.

  12. Of course not. We are all too aware of the presence of lesbians in the performing arts.EarnHoney

  13. You tried sex and came away feeling empty... You tried drugs and alcohol and awoke the next morning hung over... You tried food binges and only put on unwanted pounds... Now try God His love is immeasurable and you will never be the same again..EarnHoney

  14. This isn't to decrease the HOSPITALITY MUT estimation of conventional library enlistment, yet libraries and data are additionally evolving.

  15. Immediately drawn by writer’s exclusive way of writing.
    Mason Soiza

  16. Teamwork - the 8 secrets to achieve extraordinary results

  17. ok thanks for this post it's quite informative and I have learned new things.

  18. This mix plans graduates to exchange pertinent, valuable abilities into the workforce. HDMI to TV

  19. Great write-up, I am a big believer in commenting on blogs to inform the blog writers know that they’ve added something worthwhile to the world wide web!. Arinda Managed IT

  20. You have to show up at book signings and different occasions. It's troublesome for a marketing specialist or a radio host to state "This is an extraordinary book" and make individuals intrigued. cavewoman

  21. I think this is an informative post and it is very useful and knowledgeable. therefore, I would like to thank you for the efforts you have made in writing this article.

  22. 1st news web site this site provide a news information so more gain information. 1st news

  23. Bachelor developer this site a provider a All IT Service and Web Design and software design and SEO search engine optimizetion Service Provider So Then See Our Site And Gain Information And Service for Web Design and software design Our Software Company Our Clint’s For Spatial Discount see our site and Gain Information.
    bachelor developer

  24. . Interesting post. I Have Been wondering about this issue, so thanks for posting. Pretty cool postvidya bharati chinmaya vidyalaya jamshedpur.It 's really very nice and Useful post.Thanks