WPF Button is a frequently used UI component. In each WPF application, you will find multiple usages of buttons. Such as the close button with the close icon, or minimum button or the maximum button to resize the application.
Buttons are places to take input from users to process specific logic and produce output. If you ever used the calculator in Windows 10, 11 etc. even using buttons, each digit is a button and when you press that specific input or output is given.
In the following example, we are going to create a simple calculator for addition.
- We are adding two textboxes to take input from the user
- We are adding one button, when the user clicks the button we will process textbox values
- We are adding one label to show output when the button will be clicked
- IsNull method which is created to bypass exceptions in case no value is given and a button is clicked
Note:
After creating the button, select by mouse and press F4 to open the properties of the button. From the properties section, you can get all possible UI manipulations and events which can apply to the button.
You can also apply WPF Mouse Events, WPF Keyboard Events & RoutedCommands on the button.
You can also check all the Button Properties provided by Microsoft.
Output
WPF XAML
<Window x:Class="JWPF.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:JWPF" mc:Ignorable="d" Title="C# WPF Tutorial - By Junaid Shahid" Height="150" Width="400"> <StackPanel HorizontalAlignment="Left"> <TextBox x:Name="Value1" Width="400" Height="20"></TextBox> <TextBox x:Name="Value2" Height="20" Margin="0,10,0,0"></TextBox> <Button x:Name="Process" Click="Process_Click">Add Above</Button> <Label Name="Output">Output:</Label> </StackPanel> </Window>
C# Code
using System; using System.Windows; using System.Windows.Input; namespace JWPF { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Process_Click(object sender, RoutedEventArgs e) { Output.Content = "Output:" + (int.Parse(IsNull(Value1.Text)) + int.Parse(IsNull(Value2.Text))); } private string IsNull(string text) { if (text == null || text == "") { return "0"; } else if (text.Length == 0) { return "0"; } else { return text; } } } }
If you found any issue in the code, or want help with your project you can contact me.