Events are actions or occurrences that happen in the application, such as user interactions (clicks, key presses) or system-generated events (timers, data changes).
In WPF, events are used to handle user interactions and respond to changes in the application
Click Event
click event is pretty simple, we can define click event in xaml and then define the event handler in code behind
Key press event mostly used for textbox data entry
Key Down Event
Mostly used for add custom functionality for textbox data entry, like incrementing or decrementing a number in the textbox when up or down arrow key is pressed.
Define keydown event in xaml for textbox
<TextBlockGrid.Row="0"Grid.Column="0"Text="Number of bars:"Margin="0,0,10,10"/><TextBoxGrid.Row="0"Grid.Column="1"Text="{Binding Nos}"Margin="0,0,0,10"KeyDown="NosTextBox_KeyDown"/><TextBlockGrid.Row="1"Grid.Column="0"Text="Bar diameter (mm):"Margin="0,0,10,10"/><TextBoxGrid.Row="1"Grid.Column="1"Text="{Binding Dia}"Margin="0,0,0,10"KeyDown="DiaTextBox_KeyDown"/>
PreviewTextInput event is used to validate the input in the textbox, for example, we can use this event to allow only numbers and decimal point in the textbox.
privatevoidNosTextBox_PreviewTextInput(objectsender,TextCompositionEventArgse){// Allow only numbers and decimal pointif(!char.IsDigit(e.Text,e.Text.Length-1)&&e.Text!="."){e.Handled=true;}}
Lost Focus Event
LostFocus event is used to validate the input in the textbox when the textbox loses focus, for example, we can use this event to check if the input is a valid number and within a certain range.
Sample code to validate Bar Diameter input in the textbox when it loses focus, and update the bound property if the input is valid.
privatevoidDiaTextBox_LostFocus(objectsender,RoutedEventArgse){vartextBox=(TextBox)sender;if(double.TryParse(textBox.Text,outvardiameter)&&DesignData.AllowedDia.Contains(diameter)){//Update the bound property if the input is validDesignData.Dia=diameter;//Update the text box value from binding to ensure it reflects the bound propertytextBox.GetBindingExpression(TextBox.TextProperty)?.UpdateTarget();return;}//Reset text box value from binding if the input is invalidtextBox.GetBindingExpression(TextBox.TextProperty)?.UpdateTarget();}