.Net Maui:是否可以将字符串转换为绑定内的颜色?

gfm*_*ore 3 .net-6.0 .net-maui

参考之前的问题.Net maui:如何在绑定中引用颜色?

我有一个 CollectionView,绑定到从 SQLite 数据库填充的 ObservableCollection。

我想根据数据库表中保存的颜色字符串显示每一行

但是,我只想将颜色值存储为字符串。

是否可以将此字符串转换为绑定内的颜色或调用函数来执行此操作?

例如:

<Label Text="{Binding Name}"
       TextColor="{Binding ConvertStringToColor(ItemColor)}" />
Run Code Online (Sandbox Code Playgroud)

其中 ItemColor 是我的集合模型中的字符串,可以绑定到。

Liy*_*SFT 6

有一个名为的类ColorTypeConverter可用于将字符串转换为颜色。例如:

ColorTypeConverter converter = new ColorTypeConverter();
Color color = (Color)(converter.ConvertFromInvariantString("red"));
Run Code Online (Sandbox Code Playgroud)

因此,您可以在绑定的转换器或其他地方使用这两行代码。


gfm*_*ore 5

哇,感谢@Liyun 张的指点,找到了解决方案。为了他人的利益,这是我的解决方案。

首先,我在名为 Classes 的文件夹下创建了一个 StringToColor.cs 类(这只是我的做法)。

从https://learn.microsoft.com/en-us/dotnet/maui/xaml/fundamentals/data-binding-basics的文档中绑定值转换器段落并阅读上面和下面的内容,尽管这是一个很难遵循的示例。

using Microsoft.Maui.Graphics.Converters;
using System.Globalization;

namespace TSDZ2Monitor.Classes;

public class StringToColor : IValueConverter
{

  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
    ColorTypeConverter converter = new ColorTypeConverter();
    Color color = (Color)(converter.ConvertFromInvariantString((string)value));
    return color;
  }

  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  {
    string colorString = "White"; //TODO

    return colorString;
  }
}

Run Code Online (Sandbox Code Playgroud)

(没有使用 ConvertBack,只是虚拟代码)

(其中大部分是由 Visual Studio 自动创建的。)

在我的 ViewModel 中,我有一个 ObservableCollection,它有一个名为 ItemColor 的属性(字段)。它包含一个字符串,例如“Yellow”或“Red”等。

在我的页面 XAML 中

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:TSDZ2Monitor.ViewModels"
             xmlns:local2="clr-namespace:TSDZ2Monitor.Classes"  <---LOOK
             x:Class="TSDZ2Monitor.Pages.BluetoothPage"
             Loaded="ContentPage_Loaded"
             Title="Bluetooth Page">

  <ContentPage.Resources>
    <local2:StringToColor x:Key="StringToColor" />
  </ContentPage.Resources>
  
Run Code Online (Sandbox Code Playgroud)

在 CollectionView 中,itemsSource 绑定到我的 ObservableCollection 以及我想要以我拥有的颜色显示项目的标签中

<Label Text="{Binding Name}"
       TextColor="{Binding ItemColor, Converter={StaticResource StringToColor}, ConverterParameter=AnyStringHere }" />

Run Code Online (Sandbox Code Playgroud)

我实际上并不需要 ConverterParameter,因为它只是作为字符串出现在参数下的方法中,但我认为在此处显示它可能会有用。

所以现在我的项目可以以我设置的任何颜色显示。这是一个错误,但它有效。

:)