XAML/C#: Creating a button and an event

Creating a button for a WPF application and associating an event to it is exquisitely simple. A button can be created in the XAML with the <button> element which shares a lot of the common properties for positioning and alignment. The content property sets the text that displays on the button and the name property actually associates a name to the button.

Here’s a sample application that has a <button> element in it


This application is a simple grid layout with a couple controls that will collect information from the user. At the bottom of the application is a save button. The XAML behind the button currently looks like this:


If save button is pressed the way that it is currently set up, it won’t do anything. It’s literally just a button on the page that does a whole lot of nothing! A lot of good that does us right? This is where the wonderful world of events comes into play. The dictionary definition for an event is “enable a class or object to notify other classes or objects when something of interest occurs”… or “When something happens, do the thing(not all the things this time)”.

We can cure our button of it’s lack of events but adding the click property to it. When you add the Click=”” property, intellisense will pop up and give you the option of creating a new event handler, which so far is my preferred method.

Just to clear anything up in the picture:
The /> is the closing of the Button element and wasn’t
supposed to be that close to the property in the picture >.<

If you associated a name property with the button, then the new event handler will be ButtonName_Click. A new method will also be generated on the code behind page which will allow you to dictate what happens when the button is clicked.


Code Behind Page (MainWindow.xaml.cs)


The next step was to insert something relatively simple into the SaveButton_Click method to show that something happens when that button is clicked. Using a StringBuilder and then presenting the result, via a MessagBox, is a pretty simple solution.


This string builder allows us to append pieces of strings into one grand daddy and include the correct controls with simple bool queries. Once the string has finished being assembled, a MessageBox is able to display the result via the MessageBox.Show() method with StringBuilder.ToString() as a passed parameter.

Now when the save button is hit, the following will appear


It’s not pretty, but it does show that the event does indeed work.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s