让我向您展示一个使用值转换器的示例。在此示例中,依赖于
Foo
是 string
或可以使用 ToString()
,但您也许可以将其应用到您的案例中。
public class StringToColorDictionary : Dictionary<string, Color>
{
}
public class ObjectToColorConverter : IValueConverter
{
public StringToColorDictionary Colors { get; set; } = new();
public object Convert(object value, Type targetType, object parameter, string language)
{
return
value.ToString() is string stringValue &&
Colors.TryGetValue(stringValue, out var color)
? new SolidColorBrush(color)
: new SolidColorBrush(Microsoft.UI.Colors.Transparent);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
<Page.Resources>
<local:ObjectToColorConverter x:Key="ObjectToColorConverter">
<local:ObjectToColorConverter.Colors>
<local:StringToColorDictionary>
<Color x:Key="A">Red</Color>
<Color x:Key="B">Green</Color>
<Color x:Key="C">Blue</Color>
</local:StringToColorDictionary>
</local:ObjectToColorConverter.Colors>
</local:ObjectToColorConverter>
<DataTemplate
x:Key="ItemTemplate"
x:DataType="local:Item">
<TextBlock
Foreground="{x:Bind Foo, Converter={StaticResource ObjectToColorConverter}}"
Text="{x:Bind Foo}" />
</DataTemplate>
</Page.Resources>
<ListView
ItemTemplate="{StaticResource ItemTemplate}"
ItemsSource="{x:Bind ViewModel.Items, Mode=OneWay}" />