练习 - 创建 .NET MAUI 转换器

已完成

在本练习中,你将向之前练习中创建的天气应用添加转换器。 第一个转换器将枚举值转换为图像资源。 第二个转换器将温度从华氏度转换为摄氏度。

转换为图像

天气应用页面的当前绑定上下文是一个数据对象,其中包含描述天气预报的属性。 其中一个属性是天空状况,这是一个枚举。 显示天气信息时,应用应显示一个图标来可视化天空状况。 这意味着需要将枚举转换为图像资源。

  1. 在 Visual Studio 中打开之前练习中的天气示例项目。 如果没有副本,则可以从 GitHub 下载。

  2. 将文件夹添加到名为“Converters”的项目。

  3. 将一个新类添加到名为“WeatherConditionToImageConverter.cs”的转换器文件夹中。

  4. 在代码编辑器中打开“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 枚举作为值,并会基于该值返回一个图像资源。

  5. 打开 MainPage.xaml 文件。

  6. 在根元素上,添加一个名为 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">
    
  7. WeatherConditionToImageConverter 转换器的实例添加到页面的资源,该实例具有 WeatherConditionToImageConverter 的键:

    <ContentPage ...
    
        <ContentPage.Resources>
            <cvt:WeatherConditionToImageConverter x:Key="WeatherConditionToImageConverter" />
        </ContentPage.Resources>
    
  8. 查找名为 imgCondition<Image> 控件。

  9. Source="question.png" 属性更改为以下绑定:

    Source="{Binding Condition, Converter={StaticResource WeatherConditionToImageConverter}}"
    
  10. 运行该项目。

请注意,按“刷新”按钮时,“条件”字段将更改为一个图标:

A screenshot of the .NET MAUI app displaying the weather forecast with a sun icon for the sky condition.