Exercise - Create a .NET MAUI converter
In this exercise, you add a converter to the Weather app created in the previous exercise. The first converter converts an enumeration value to an image resource. The second converter converts the temperature from Fahrenheit to Celsius.
Convert to an image
The current binding context of the weather app's page is a data object with properties describing the weather forecast. One of those properties is the sky condition, which is an enumeration. When weather information is displayed, the app should show an icon to help the user visualize the sky condition. To show these icons, the enumeration needs to be converted to an image resource.
Open the Weather Sample project from the previous exercise in Visual Studio. If you don't have a copy, you can download it from GitHub.
Add a folder to the project named Converters.
Add a new class to the Converters folder named WeatherConditionToImageConverter.cs.
Open WeatherConditionToImageConverter.cs in the code editor and replace all the code with the following code:
using System.Globalization; using WeatherClient.Models; namespace WeatherClient.Converters; internal class WeatherConditionToImageConverter : IValueConverter { public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture) { WeatherType weatherCondition = (WeatherType)value!; return weatherCondition switch { Models.WeatherType.Sunny => ImageSource.FromFile("sunny.png"), Models.WeatherType.Cloudy => ImageSource.FromFile("cloud.png"), _ => ImageSource.FromFile("question.png") }; } public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) => throw new NotImplementedException(); }
This code defines the
WeatherConditionToImageConverter
converter in theWeatherClient.Converters
namespace. This converter expects theWeatherType
enumeration as the value, and returns an image resource based on that value.Open the MainPage.xaml file.
On the root element, add a new XML namespace named
cvt
and map it to the .NET namespaceWeatherClient.Converters
.<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:cvt="clr-namespace:WeatherClient.Converters" x:Class="WeatherClient.MainPage">
Add an instance of the
WeatherConditionToImageConverter
converter to the page's resources, with the key ofWeatherConditionToImageConverter
:<ContentPage ... <ContentPage.Resources> <cvt:WeatherConditionToImageConverter x:Key="WeatherConditionToImageConverter" /> </ContentPage.Resources>
Find the
<Image>
control inGrid.Row="0"
.Change the
Source="question.png"
property to the following binding:Source="{Binding Condition, Converter={StaticResource WeatherConditionToImageConverter}}"
Run the project.
Notice that when you press the Refresh button, the Condition field changes to an icon: