Skip to content

Build a c# currency converter application using WPF in C# with static data

  • CSharp

In this article, you will learn how to create a C# Currency Converter using WPF. All you need to have is a good knowledge of C#.

If you are interested in becoming a professional software developer, make sure to check out our courses!

What is a Currency Converter?

Currency Converter is a WPF application designed to convert one currency into another to check its corresponding value. The program is generally a part of a web site, or it forms a mobile app. It is based on the current market or bank exchange rates.

To convert one currency into another, all you need to do is enter an amount of money (e.g., ‘1000’) and choose the currency and select the monetary value (e.g. “United States Dollar”). You can try with the multiple monetary selections. The application then calculates the entered amount with the exchange value and displays the corresponding amount of money.

What is WPF?

WPF stands for Windows Presentation Foundation. And, the WPF is a UI framework that creates desktop client applications. Also, it is a part of .NET. It supports a broad set of application development features, including resources, an application model, layout, data binding, documents, controls, graphics, and security in terms of the WPF development platform.

The WPF uses Extensible Application Markup Language (XAML) to provide a declarative model for application programming.

Technical Requirements for building a C# Currency Converter

Before moving further, I assume that you must be familiar with below-listed things:

1. Programming basics

To build this application, I will be using the C# language to write the code for the core logic.

The C# is a general-purpose, modern and object-oriented programming language pronounced as “C sharp.” Microsoft developed it. C# is widely used for developing web applications and desktop applications.

2. IDE (Integrated development environment)

Visual studio is the best editor for writing code and develop websites, web apps, software, mobile apps.

Click here to download Visual Studio

Step by step guide for building a C# Currency Converter application using WPF

Create a new project

  • Firstly, open Visual Studio and select Create a new project under the Get started menu.
C# Currency Converter
  • Select WPF App (.Net Framework)
  • Click on the Next button.
C# Currency Converter

Configure project

  • Enter the project name of your choice. I am using the project name CurrencyConverter_Static.
  • Select the location where you want to save your project.
  • Click on the create button.
C# Currency Converter

As you have completed the project creation steps, the Visual Studio creates the project with some default pages.

  • MainWindow.xaml
  • MainWindow.xaml.cs
  • App.xaml
  • App.config
  • MainWindow.xaml file defines a WPF application and any application resources. You can also use this file to specify the UI. In this case – MainWindow.xaml, it automatically shows when the application starts.
  • MainWindow.xaml.cs is a file with a code-behind file that contains code that handles the events declared in MainWindow.xaml, also, the file contains a partial class for the window defined in XAML.
  • App.xaml is also the place to subscribe to essential application events, like application start, unhandled exceptions, etc. App.xaml is the declarative starting point of your application. The Code-behind file is called App.xaml.cs. It works a lot like Windows, where the two files are partial classes. They exist together to allow you to work in both markup (XAML) and Code-behind.
  • App.config files are XML files that can be changed as per requirement. The administrator can control which protected resources an application can access, which versions of assemblies an application will use, and where remote applications and objects are located. Developers can put settings in configuration files. e.g., the connection string for connecting with the database.
  • The default code generated in MainWindow.xaml

Designing the C# Currency Converter application

Now, change the following properties in the XAML code for the NavigationWindow element:

  • First, set the Title property value to “Currency Converter.”
  • Remove default Height and Width from window tag properties and add SizeToContent=”WidthAndHeight” property to set window form according to the content size.
  • Set up WindowStartupLocation property to “CenterScreen” to set the center position of the window.
  • Set up Icon=”Images\money.png” property to set the application’s icon and so will be visible on the title bar.

After making the above changes, the property will look as below

  • Add the below code between the <Grid></Grid> tag.
  • The Grid Panel provides a flexible area which consists of rows and columns also child elements can be arranged in tabular form. The items can be added to any specific row and column by using Grid.Row and Grid.Column properties.
  • By default, the Grid panel is created with one row and one column. And, the Multiple rows and columns are created by RowDefinitions and ColumnDefinitions properties.

Borders in WPF works a bit differently. The Border in XAML has its control that can be applied to other controls or XAML elements. For placing a border around an element, WPF provides the Border element, which is similar to other WPF elements. Border has WidthHeightBackground, and HorizontalAlignment and VerticalAlignment properties.

Besides the common properties, the Border has two properties that make Border look like a border, which is BorderThickness and BorderBrush

BorderBrush is a property that represents the brush that is used to draw the Border. BorderThickness is a property which represents the thickness of the Border.

The Corner Radius is a property used to indicate the degree to which the corners of the border will be rounded. For creating curved borders for the windows, you need to use CornerRadius property of the ChromelessWindow. Also, the default value is zero, which implies sharp corners.

  • The linear gradient brush paints an area with a linear gradient. The default value of the linear gradient is diagonal. The StartPoint and EndPoint properties of the LinearGradientBrush represent the start and endpoints of a gradient.
  • The gradient stop properties:
    • Color – Property to set color is described using a predefined color name or hexadecimal notation.
    • OffSet – Offset determines the position of the color between your start and endpoints.

The Rectangle object represents a rectangle shape. Which draws a rectangle with the given height and width. Also, the width and height properties of the rectangle class represent the width and height of a rectangle. And, the Fill property fills the interior of a rectangle.

Now, let’s design the StackPanel.

  • The Stackpanel is a useful and straightforward layout panel in XAML. In the stack panel, child elements can be arranged in a single line, either horizontally or vertically, based on the “Orientation” property. Stackpanel is used whenever any list is about to be created.
  • Any control in WPF can be placed within a grid by using its Grid.Row and Grid.Column properties that represent which column and which row a control will be placed inside. The values of rows and columns start with 0. That means, if there are five rows in a grid, the first row will be represented by the number 0.
  • In the stackpanel tag, add a control that is used in our program. e.g., Label, Textbox, Combobox, Button, Image, etc.
  • Set the Controls property as per requirement. e.g., Height, Width, HorizontalAlignment, VerticalAlignment, Margin, FontSize, Foreground, Content, Name, etc.
  • Here I used the lblCurrency label to display converted currency name and converted currency value.
  • fa:ImageAwesome tag is used to show the icon. To use this control first, you need to add “fontawesome.wpf” to the Library.
    • Open solution explorer.
    • Right-click on the project name. Select “Manage Nuget Packages.” Select the Browse tab and search for “fontawesome.wpf” and select it and click on the install button.
  • Fontawesome gives you scalable vector icons that can instantly be customized.
  • The Click attribute of the Button element adds the click event handler. The Click=”Convert_Click” is raised when the Button control is clicked.
  • Between the button, tag put <Button.Background> tag. it is used to set the button background color.
  • LinearGradientBrush paint an area with a linear gradient. The linear gradient brush object represents a linear gradient brush. The default value of linear-gradient value is diagonal. The StartPoint and EndPoint properties of the LinearGradientBrush represent the start and endpoints of a gradient.
  • The gradient stop properties:
    • Color – in this property, you can set a color with a color name or code.
    • OffSet – Offset determines the position of the color between your start point and endpoint.
  • In the “App.xaml” page, set the property of button border rounded. “App.xaml” page is default created when you create a WPF Project.
    • Between the <Application.Resources></Application.Resources> tag you need to add the code below.
    • x:key property set name “ButtonRound.” To use this in the button, use Style=”{StaticResource ButtonRound}” property.
    • TargetType property sets the target of the controls you want to apply this style to the property.

App.xaml Page

MainWindow.xaml file final code will look like below:

Output:

Application core part

  • The default code added in MainWindow.xaml.cs by Visual Studio is as below:

The namespace is designed to provide a way to keep one set of names separate from another. This class names declared in one namespace does not conflict with the same class names declared in another.

The namespace definition begins with the keyword namespace.

It is a partial class is a special feature of C# which provides a special ability to implement the functionality of a single class into multiple files. When the application is compiled all the files are combined into a single class file.

The partial class is created by using a partial keyword and the keyword is also useful to split the functionality of interfaces, methods, or structure into multiple files.

InitializeComponent() is a method automatically written for you by the Form Designer when you create/change your forms. Now you need to drag controls to the Form in Visual Studio. Behind the scenes, Visual Studio adds code to the InitializeComponent method, which is called in the Form constructor.

Remove unnecessary namespace from our code.

Bind Currency From and To Combobox

Create a private method as BindCurrency().

Private is an access modifier. Type or member can be accessed only by code in the same class or struct.

The Void keyword is used for the method signatures to declare a method that does not return any value. The method declared with the void return type cannot provide any arguments to any return statements they contain.

The BindCurrency() is a name of method.

Create an object of DataTable as below:

  • Import namespace using System.Data on top of the MainWindow.xaml.cs.
  • The DataTable object represents tabular data as an in-memory, tabular cache of rows, columns, and constraints.
  • DataTable dtCurrency = new DataTable(); Using this code you are creating an empty data table for which the TableName property is set to dtCurrency. You can use this property to access this data table from a DataTable Collection.
  • In DataTable add two columns:
    • Text
    • Value
  • Add some rows with data in data table:
  • After adding data to the DataTable, assign data to the Combobox using the ItemSource attribute.
  • Set the Combobox DisplayMemberPath attribute, which you want to show in Combobox as display text.
  • Set the Combobox SelectedValuePath attribute, which you want to set in Combobox as value.
  • Make sure both properties are set with the same as the DataTable column name.
  • After adding the BindCurrency() method call it in MainWindow() method. Because when the application run MainWindow() method is called first.

Output:

  • Create a new method for Clearcontrols().
  • This method is used to clear all control data which the user entered.
  • Add the method in the MainWindow() method.
  • Create a method NumberValidationTextBox() . The method is used for the Amount textbox only, which allows the use of numbers. I am using Regular Expression.
  • Import namespace using System.Text.RegularExpressions on top of the MainWindow.xaml.cs for use regular expression.
  • Import using System.Windows.Input namespace. TextCompositionEventArgs deals with changes while composing the text, so it has many properties dealing with the text and what is explicitly changing.

Calculation of Currency Converter

  • Add the convert button click event. On clicking on the convert button this event fire.
  • Declare a variable ConvertedValue with the double datatype. It’s used to store the converted value and show it in the label.
  • Check validation if the Amount textbox is blank. If so, then it shows the message “please enter amount.”
  • Check validation if the user did not select any currency from FromCurrency Combobox, then it shows the message “Please select currency from.”
  • Check validation if the user did not select any currency from ToCurrency Combobox, then it shows the message “Please select currency to.”
  • Check the condition if the from currency and to currency have the same currency name then store the amount textbox value in the convertedvalue variable. e.g., Enter 10 in the Amount textbox, then select in from currency Combobox USD and to currency Combobox USD, then show the currency name with the converted value. E.g. “USD 10.000”
  • If the From Currency and the To Currency is not the same, then else part will be executed.
  • The From Currency value will be multiplied (*) with the Amount Textbox value and then that total divided(/) To Currency value and it’s store in ConvertedValue variable.
  • Display the converted Currency name with ConvertedValue in the label.
  • Create a clear button click event.
  • Call the ClearControls() method to clear all controls from the input which the user entered.

MainWindow.xaml.cs final code

Output:

Summary

  • In this article, you have learned about the creation of the Currency Converter application in WPF. As of now, we used static data to assign currency value. In the upcoming, I will show you doing it using the database.

Leave a Reply

Your email address will not be published. Required fields are marked *

Enter your email and we will send you the PDF guide:
Enter your email and we will send you the PDF guide