LA.NET [EN]

Nov 19

A friend of mine asked me about events and XAML: can we setup event handlers in XAML? And the answer is, yes, you can. Here’s a quick example of how you can handle the click event of a button:

<Button Click="Button_Click"></Button>

And yes, you must define the Button_Click method in your code-behind file (note that you could do it inline – ie, in the XAML file – if you’re using WPF). I must confess that I’m not really a fan of this approach since I prefer to put all my code in the code-behind file. For making it work, I’ll need to change the previous code slightly by adding a name to the button:

<Button x:Name="bt"></Button>

And now, from within the constructor, I can setup my event handler like this:

bt.Click += Button_Click;

Final note: in the real world, I’ll probably end up with a Lambda expression for simple handlers. As you can see, setting up handlers from the XAML is possible (the syntax is the same as you’ve got for props) but I don’t really recommend it. And that’s it for now. In the next post, we’ll talk about Silverlight’s markup extension support. Stay tuned.

Leave a Reply

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


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>