BC200405554
CS411
Assignment no: 02
Problem Statement:
You are required to develop a WPF application in C# that converts a temperature from
Fahrenheit to Celsius. The application should consist of a clean and simple interface built using
WPF in xaml (MainWindow.xaml), and the conversion logic should be implemented in C#
(MainWindow.xaml.cs).
Solution:
1. XAML Code:
<Window x:Class="BC200405554.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:BC200405554"
mc:Ignorable="d"
Title="Temperature Converter" Height="450" Width="800">
<Grid Margin="20">
<StackPanel VerticalAlignment="Center">
<!-- VU ID Label -->
<Label Content="BC200405554"
FontSize="24"
FontWeight="Bold"
HorizontalAlignment="Center"
HorizontalContentAlignment="Center" />
<!-- Input Label -->
<Label Content="Input Fahrenheit:"
FontSize="16"
FontWeight="Bold" />
<!-- Input Textbox -->
<TextBox x:Name="FahrenheitInput"
Height="40"
Padding="0, 10, 0, 5"
Margin="0,0,0,15"
FontSize="14" TextChanged="FahrenheitInput_TextChanged" />
<!-- Convert Button -->
<Button Content="To Celsius"
Background="Green"
Foreground="White"
FontWeight="Bold"
FontSize="16"
Height="40"
Click="ConvertButton_Click" />
<!-- Result Label -->
<Label x:Name="ResultLabel"
FontSize="18"
FontWeight="Bold"
HorizontalContentAlignment="Left" />
</StackPanel>
</Grid>
</Window>
2. C# Code:
using System;
using System.Windows;
using System.Windows.Controls;
namespace BC200405554
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void ConvertButton_Click(object sender, RoutedEventArgs e)
{
try
{
double fahrenheit = double.Parse(FahrenheitInput.Text);
double celsius = (fahrenheit - 32) * 5 / 9;
ResultLabel.Content = $"Result: {celsius:F2} °C";
}
catch (Exception)
{
MessageBox.Show("Please enter a valid number for Fahrenheit.", "Invalid Input",
MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void FahrenheitInput_TextChanged(object sender, TextChangedEventArgs e)
{
}
}
}
3. Screenshot: