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...
<controls:Pivot
 Title="MY APPLICATION"
 SelectionChanged="thisPivot_SelectionChanged"
 Name="pivot">

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

Me:
So, you fixed the issue!

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

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

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

Me:
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

Friend:
"wire up"
that's new for me!

Me:
what did you do before this?

Friend:
nothing
just defined the handler

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

Friend:
yes yes :P

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

Friend:
yeah, of course!

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

Friend:
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

Me:
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:
object.Event+=EventHandler;
(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?

Me:
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=SelectionChanged;
if(handler!=null)
   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

54 comments:

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

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. 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

    ReplyDelete
  4. 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 world.best under

    ReplyDelete
  5. 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 https://internetprivatsphare.ch

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

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

    ReplyDelete
  8.  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

    ReplyDelete
  9. This comment has been removed by the author.

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

    ReplyDelete
  11. 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

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

    ReplyDelete
  13. Teamwork - the 8 secrets to achieve extraordinary results

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

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

    ReplyDelete
  16. 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

    ReplyDelete
  17. 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

    ReplyDelete
  18. 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. vpnveteran.com

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

    ReplyDelete
  20. . 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

    ReplyDelete
  21. I admit, I have not been on this web page 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 deze website

    ReplyDelete
  22. I'm really impressed about the info you provide in your articles. If you want to invest in suits and be stress-free, then you should shake hands with us. We are providing great clothing in the most reasonable price range that you wouldn’t find anywhere else. Put your trust in us as your supplier since we are the prominent printed stickers uk You can rely on us for the clothing problems we assure you we will never let our customers down.

    ReplyDelete
  23. This plenitude of solar power implies there's more than we'll ever require. Zonnepanelen

    ReplyDelete
  24. I'm sure you know how rewarding it is to sign onto Facebook and see that red notification at the top of the screen, or even more directly how rewarding playing games on your computer can be as you accumulate more "accomplishments."arlo

    ReplyDelete
  25. Going virtual gives an effectively utilized medium to these necessities stage hire Yorkshire

    ReplyDelete
  26. All things considered, utilizing call tracking programming is an extraordinary method to deal with your organization without every one of the inconveniences that originate from working with the phone organization. https://callgear.com/product/web2call/

    ReplyDelete
  27. If you have your customer's email database, then you can use email marketing to grow your business.Email List

    ReplyDelete
  28. Ok, my point, Have a long-term plan, don't expect to make it happen in the first few months and follow a course of action for at least a year. Travel

    ReplyDelete
  29. bachelor developer software company
    hello brother's your bachelor developer software company provide high qualty software provider ricently create a school menegment system provide a very low bujet for school's with a androide application.

    SEO
    hello brother's your software company provide a high quality seo websites ranking on page and off page.

    graphic design
    hello brother's our software company provide graphic designing service by bachelor developer.

    software company in hyderabad
    software company in pakistan

    hello brother's your bachelor developer software company provide high qualty software provider ricently create a school menegment system provide a very low bujet for school's with a androide application.
    Web design company

    bachelor developer software company provide high quality software and websites and more services.
    cheap website design pakistan

    software house in pakistan

    software house in sindh

    web development company pakistan

    software house in latifabad

    ReplyDelete
  30. Thanks for the blog loaded with so many information. Stopping by your blog helped me to get what I was looking for. rouge planet

    ReplyDelete
  31. 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.
    먹튀사이트

    ReplyDelete
  32. Thanks for the post and great tips: even I also think that hard work is the most important aspect of getting success. What plans do ActiveCampaign Offer

    ReplyDelete
  33. The post is written in very a good manner and it contains many useful information for me.
    email finder

    ReplyDelete
  34. 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!.. email search tool

    ReplyDelete
  35. With a great many people connected constantly, I regularly wonder what impact technology is having on our children.cromare plastica

    ReplyDelete
  36. Thank you for your post, I look for such article along time, today i find it finally. this post give me lots of advise it is very useful for me. email search tool

    ReplyDelete
  37. Long range informal communication technologies help singular clients to frame online interpersonal organizations with different clients.Best Night Vision Binoculars

    ReplyDelete
  38. Hey, I am so thrilled I found your blog, I am here now and could just like to say thank for a tremendous post and all round interesting website. Please do keep up the great work. I cannot be without visiting your blog again and again. click here

    ReplyDelete
  39. Thank you for your post, I look for such article along time, today i find it finally. this post give me lots of advise it is very useful for me. Team Training

    ReplyDelete
  40. I am looking for and I love to post a comment that "The content of your post is awesome" Great work! ceo email

    ReplyDelete
  41. the whole lot has its fee. thank you for sharing this informative trace following us. precise works! Buy Email List

    ReplyDelete
  42. So Christian and God-respecting chapel gatherings and individual festivals for the introduction of Jesus, even in December, are okay in my book. Diego Martir

    ReplyDelete
  43. In addition, Cell Site Simulators will log IMSI numbers (unique identification numbers) of all mobile devices within a certain radius. Some advanced Cell Site Simulators may have upgraded features that allow law enforcement to intercept or even modify communications data. CUAS

    ReplyDelete
  44. Chris O’Donnell, Dy. Asst. Defense Secretary for weapon portfolio and platform management stated that industry leaders, academia, several government agencies operating within the department & combatant commanders were all unaware of who they were reporting to. Cellular Monitoring

    ReplyDelete
  45. I should say only that its awesome! The blog is informational and always produce amazing things. Managed Websites

    ReplyDelete
  46. Beside the advantages of solar panels to the earth, solar panel establishment is additionally a serious extraordinary interest in itself. It might cost a serious large aggregate of cash toward the start, yet over the long haul all the underlying cost rapidly pays for itself.Zonnepanelen kopen

    ReplyDelete
  47. 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. Big thanks for the useful info. skytechosting.com

    ReplyDelete
  48. Your blog provided us with valuable information to work with. Each & every tips of your post are awesome. Thanks a lot for sharing. Keep blogging.. nest

    ReplyDelete
  49. The thought with respect to content informing to the mobile clients was found toward the start of the 1980s. SMS API Service

    ReplyDelete
  50. Your blog provided us with valuable information to work with. Each & every tips of your post are awesome. Thanks a lot for sharing. Keep blogging.
    technology

    ReplyDelete