English 中文(简体)
XAML - Event Handling
  • 时间:2024-12-22

XAML - Event Handpng


Previous Page Next Page  

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 apppcation 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 apppcation based on the requirement of that apppcation, but the most commonly used events are those which are related to mouse and keyboard such as,

    Cpck

    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 pnked 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 cpck event. Given below is the XAML implementation for Button control which is created and initiapzed with some properties and a Cpck event (Cpck="OnCpck").

<Window x:Class = "XAMLEventHandpng.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 = "Cpck" Cpck = "OnCpck" 
         Width = "150" Height = "30" HorizontalApgnment = "Center" /> 
   </Grid>
   
</Window> 

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

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

namespace XAMLEventHandpng {
   /// <summary> 
      /// Interaction logic for MainWindow.xaml 
   /// </summary> 
	
   pubpc partial class MainWindow : Window {
      pubpc MainWindow() { 
         InitiapzeComponent(); 
      }
      private void OnCpck(object sender, RoutedEventArgs e) { 
         MessageBox.Show("Button is cpcked!"); 
      } 
   }
}

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

Event Handpng

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

Event Handpng Function

Now let’s have a look at a pttle 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 Cpck.

<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 = "_Itapc" IsCheckable = "True" 
                  Checked = "Itapc_Checked" Unchecked = "Itapc_Unchecked" /> 
               <Separator /> 
               <MenuItem Header = "Increase Font Size" Cpck = "IncreaseFont_Cpck" />
               <MenuItem Header = "_Decrease Font Size" Cpck = "DecreaseFont_Cpck" /> 
            </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 cpcked.

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>
	
   pubpc partial class MainWindow : Window {
      pubpc MainWindow() { 
         InitiapzeComponent(); 
      }
      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 Itapc_Checked(object sender, RoutedEventArgs e) { 
         textBox1.FontStyle = FontStyles.Itapc; 
      }
      private void Itapc_Unchecked(object sender, RoutedEventArgs e) { 
         textBox1.FontStyle = FontStyles.Normal; 
      }
      private void IncreaseFont_Cpck(object sender, RoutedEventArgs e) { 
         if (textBox1.FontSize < 18) { 
            textBox1.FontSize += 2; 
         } 
      }
      private void DecreaseFont_Cpck(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

Cpck

Occurs when a button control is cpcked. (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