There are many types of events, but some of the most commonly used are there to respond to the user's interaction with your application using the mouse or the keyboard. On most controls you will find events like KeyDown, KeyUp, MouseDown, MouseEnter, MouseLeave, MouseUp and several others.
We will look more closely at how events work in WPF, since this is a complex topic, but for now, you need to know how to link a control event in XAML to a piece of code in your Code-behind file. Have a look at this example:
<Window x:Class="WpfTutorialSamples.XAML.EventsSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="EventsSample" Height="300" Width="300">
<Grid Name="pnlMainGrid" MouseUp="pnlMainGrid_MouseUp" Background="LightBlue">
</Grid>
</Window>
Notice how we have subscribed to the MouseUp event of the Grid by
writing a method name. This method needs to be defined in code-behind,
using the correct event signature. In this case it should look like
this:
private void pnlMainGrid_MouseUp(object sender, MouseButtonEventArgs e)
{
MessageBox.Show("You clicked me at " + e.GetPosition(this).ToString());
}
The MouseUp event uses a delegate called MouseButtonEventHandler,
which you subscribe to. It has two parameters, a sender (the control
which raised the event) and a MouseButtonEventArgs object that will
contain useful information. We use it in the example to get the position
of the mouse cursor and tell the user about it.
Fortunately, Visual Studio can help us to generate a correct event
handler for an event. The easiest way to do this is to simply write the
name of the event in XAML and then let the IntelliSense of VS do the
rest for you:
No comments:
Post a Comment