XAML - Event Handling



The general concept of events in XAML is similar to events in other popular programming languages such as .NET and C++. In XAML, all of the controls expose some events so that they can be subscribed for specific purposes.

Whenever an event takes place, the application will be notified and the program can react to them, e.g., close buttons are used to close a dialog.

There are many types of events that can be subscribed for different behaviors of an application based on the requirement of that application, but the most commonly used events are those which are related to mouse and keyboard such as,

  • Click
  • MouseDown
  • MouseEnter
  • MouseLeave
  • MouseUp
  • KeyDown
  • KeyUp

In this chapter, we will use some of the basic and most commonly used events to understand how an event of a specific control can be linked to the code behind where the behavior will be implemented depending on what the user wants to do when a specific event occurs.

Let’s have a look at a simple example of a button click event. Given below is the XAML implementation for Button control which is created and initialized with some properties and a Click event (Click="OnClick").

<Window x:Class = "XAMLEventHandling.MainWindow" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   Title = "MainWindow" Height = "350" Width = "604"> 
	
   <Grid> 
      <Button x:Name = "button1" Content = "Click" Click = "OnClick" 
         Width = "150" Height = "30" HorizontalAlignment = "Center" /> 
   </Grid>
   
</Window> 

Whenever this button is clicked, it will fire an OnClick event and you can add any type of behavior as a response to the Click. Let’s have a look at the OnClick event implementation which will show a message when this button is clicked.

using System; 
using System.Windows; 
using System.Windows.Controls;  

namespace XAMLEventHandling {
   /// <summary> 
      /// Interaction logic for MainWindow.xaml 
   /// </summary> 
	
   public partial class MainWindow : Window {
      public MainWindow() { 
         InitializeComponent(); 
      }
      private void OnClick(object sender, RoutedEventArgs e) { 
         MessageBox.Show("Button is clicked!"); 
      } 
   }
}

When you compile and execute the above code, it will produce the following output −

Event Handling

When you click on the button, the click (OnClick) event will be fired and the following message will be displayed.

Event Handling Function

Now let’s have a look at a little bit complex example where multiple events are handled.

Example

The following example contains a textbox with ContextMenu which manipulates the text within the textbox.

The following XAML code creates a TextBox, a ContextMenu, and MenuItems with some properties and events such as Checked, Unchecked, and Click.

<Window x:Class = "XAMLContextMenu.MainWindow" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   Title = "MainWindow" Height = "350" Width = "604"> 
	
   <Grid> 
      <TextBox Name = "textBox1" TextWrapping = "Wrap" Margin = "10" Grid.Row = "7"> 
         Hi, this is XAML tutorial. 
         <TextBox.ContextMenu>
         
            <ContextMenu>
               <MenuItem Header = "_Bold" IsCheckable = "True" 
                  Checked = "Bold_Checked" Unchecked = "Bold_Unchecked" /> 
               <MenuItem Header = "_Italic" IsCheckable = "True" 
                  Checked = "Italic_Checked" Unchecked = "Italic_Unchecked" /> 
               <Separator /> 
               <MenuItem Header = "Increase Font Size" Click = "IncreaseFont_Click" />
               <MenuItem Header = "_Decrease Font Size" Click = "DecreaseFont_Click" /> 
            </ContextMenu> 
				
         </TextBox.ContextMenu>
      </TextBox>
   </Grid> 
	
</Window> 

Here is the implementation in C# for the different events which will be fired whenever a menu item is checked, unchecked, or clicked.

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Data;  

namespace XAMLContextMenu { 
   /// <summary> 
      /// Interaction logic for MainWindow.xaml 
   /// </summary>
	
   public partial class MainWindow : Window {
      public MainWindow() { 
         InitializeComponent(); 
      }
      private void Bold_Checked(object sender, RoutedEventArgs e) { 
         textBox1.FontWeight = FontWeights.Bold; 
      }
      private void Bold_Unchecked(object sender, RoutedEventArgs e) { 
         textBox1.FontWeight = FontWeights.Normal; 
      }
      private void Italic_Checked(object sender, RoutedEventArgs e) { 
         textBox1.FontStyle = FontStyles.Italic; 
      }
      private void Italic_Unchecked(object sender, RoutedEventArgs e) { 
         textBox1.FontStyle = FontStyles.Normal; 
      }
      private void IncreaseFont_Click(object sender, RoutedEventArgs e) { 
         if (textBox1.FontSize < 18) { 
            textBox1.FontSize += 2; 
         } 
      }
      private void DecreaseFont_Click(object sender, RoutedEventArgs e) { 
         if (textBox1.FontSize > 10) { 
            textBox1.FontSize -= 2; 
         } 
      }
   }
}

When you compile and execute the above code, it will produce the following output −

ContextMenu Output

We recommend you to execute the above example code and experiment with some other events.

Events

Sr.No. Controls & Description
1

Checked

Fires when a ToggleButton is checked. (Inherited from ToggleButton)

2

Click

Occurs when a button control is clicked. (Inherited from ButtonBase)

3

ContextMenuClosing

Occurs just before any context menu on the element is closed. (Inherited from FrameworkElement.)

4

ContextMenuOpening

Occurs when any context menu on the element is opened. (Inherited from FrameworkElement.)

5

DataContextChanged

Occurs when the value of the FrameworkElement.DataContext property changes. (Inherited from FrameworkElement)

6

DragEnter

Occurs when the input system reports an underlying drag event with this element as the target. (Inherited from UIElement).

7

DragLeave

Occurs when the input system reports an underlying drag event with this element as the origin. (Inherited from UIElement)

8

DragOver

Occurs when the input system reports an underlying drag event with this element as the potential drop target. (Inherited from UIElement)

9

DragStarting

Occurs when a drag operation is initiated. (Inherited from UIElement)

10

DropCompleted

Occurs when a drag-and-drop operation is ended. (Inherited from UIElement)

11

DropDownClosed

Occurs when the drop-down portion of the ComboBox closes.

12

DropDownOpened

Occurs when the drop-down portion of the ComboBox opens.

13

GotFocus

Occurs when a UIElement receives focus. (Inherited from UIElement)

14

Holding

Occurs when an otherwise unhandled Hold interaction occurs over the hit test area of this element. (Inherited from UIElement)

15

Intermediate

Fires when the state of a ToggleButton is switched to the indeterminate state. (Inherited from ToggleButton)

16

IsEnabledChanged

Occurs when the IsEnabled property changes. (Inherited from Control)

17

KeyDown

Occurs when a keyboard key is pressed while the UIElement has focus. (Inherited from UIElement)

18

KeyUp

Occurs when a keyboard key is released while the UIElement has focus. (Inherited from UIElement)

19

LostFocus

Occurs when a UIElement loses focus. (Inherited from UIElement)

20

ManipulationCompleted

Occurs when a manipulation on the UIElement is complete. (Inherited from UIElement)

21

ManipulationDelta

Occurs when the input device changes position during a manipulation. (Inherited from UIElement)

22

ManipulationInertiaStarting

Occurs when the input device loses contact with the UIElement object during a manipulation and inertia begins. (Inherited from UIElement)

23

ManipulationStarted

Occurs when an input device begins a manipulation on the UIElement. (Inherited from UIElement)

24

ManipulationStarting

Occurs when the manipulation processor is first created. (Inherited from UIElement)

25

SelectionChanged

Occurs when the text selection has changed.

26

SizeChanged

Occurs when either the ActualHeight or the ActualWidth property changes value on a FrameworkElement. (Inherited from FrameworkElement)

27

Unchecked

Occurs when a ToggleButton is unchecked. (Inherited from ToggleButton)

28

ValueChanged

Occurs when the range value changes. (Inherited from RangeBase)

Advertisements