练习 - 创建 .NET MAUI 转换器
在本练习中,你将向之前练习中创建的天气应用添加转换器。 第一个转换器将枚举值转换为图像资源。 第二个转换器将温度从华氏度转换为摄氏度。
转换为图像
天气应用页面的当前绑定上下文是一个数据对象,其中包含描述天气预报的属性。 其中一个属性是天空状况,这是一个枚举。 显示天气信息时,应用应显示一个图标来帮助用户可视化天空状况。 要显示这些图标,需要将枚举转换为图像资源。
在 Visual Studio 或 Visual Studio Code 中打开之前练习中的天气示例项目。
将文件夹添加到名为“Converters”的项目。
将一个新类添加到名为“WeatherConditionToImageConverter.cs”的转换器文件夹中。
在代码编辑器中打开“WeatherConditionToImageConverter.cs”,并将所有代码替换为以下代码:
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(); }
此代码定义
WeatherClient.Converters
命名空间中的WeatherConditionToImageConverter
转换器。 此转换器预期以WeatherType
枚举作为值,并会基于该值返回一个图像资源。打开 MainPage.xaml 文件。
在根元素上,添加一个名为
cvt
的新 XML 命名空间并将其映射到 .NET 命名空间WeatherClient.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">
将
WeatherConditionToImageConverter
转换器的实例添加到页面的资源,该实例具有WeatherConditionToImageConverter
的键:<ContentPage ... <ContentPage.Resources> <cvt:WeatherConditionToImageConverter x:Key="WeatherConditionToImageConverter" /> </ContentPage.Resources>
在
Grid.Row="0"
中找到<Image>
控件。将
Source="question.png"
属性更改为以下绑定:Source="{Binding Condition, Converter={StaticResource WeatherConditionToImageConverter}}"
运行该项目。
请注意,按“刷新”按钮时,“条件”字段将更改为一个图标: