It’s finally time to quit talking about WPF Containers, and start getting into some of the controls. The first one we’ll hit is the hardest working control in show business, the WPF Button.
I’m sure you’re thinking “what’s so hard about a button?” After all, you slap a button tag on a form like this:
Title=“Buttons“ Height=“83“ Width=“194“
<Button>Click Me Baby!</Button>
I created a window named ButtonWindow, and added a StackPanel with one button. This will give you something like this:
Simple and easy, but there’s much more to the button. First off, you can change the point at which the click event actually fires. The button has a ClickMode property you can set that controls this. The default is “Release”, which pretty much acts as you expect. The other two values are Press and Hover. When the button looks like a button, you would probably want to use release, however it’s possible to morph the button to a graphic of some sort. In that case it might be more intuitive to fire when the button is first pressed, and not when the user releases the mouse.
Speaking of the click, just how do you react to a WPF event in C# anyway? Good question, I thought you’d never ask.
All you have to do is indicate the name of the event you want to respond to, then pass in a string value which is the name of the method to route to. In your XAML, alter the Button line to look like this:
<Button Click=“Baby_Click“>Click Me Baby!</Button>
Now we need a little C# code to respond. Open the code behind class (in my case ButtonWindow.xaml.cs). Now add a new method:
private void Baby_Click(object sender, RoutedEventArgs e)
MessageBox.Show(“Hi There!”,“Baby was clicked!”);
WPF Events must match a certain signature. They will need to have a return type of void (or will be a SUB for you VB folks). They will also accept two arguments, an object that indicates what the sender of the event was, and a set of event arguments encased in the RoutedEventArgs variable, traditionally called e.
Here were doing something pretty simple, and showing a message box.
There’s lots more we can do with the button, but we’ll save that for a more advanced day. Today I just wanted to cover the basics of the button, as it’s one control that will likely see a lot of use in your toolbox.