列表视图项的替代颜色

Alternative color for listview items

本文关键字:颜色 视图 列表      更新时间:2023-10-16

我的xaml文件中有下面的列表视图。它绑定了一个平台集合。其中包含警告和错误消息。文本块前景色设置为红色。我需要为不同的消息设置不同的颜色。如何为各种消息设置不同的颜色?

<ListView x:Name="mylist" Width="578" ScrollViewer.VerticalScrollMode="Enabled" ScrollViewer.HorizontalScrollBarVisibility="Disabled" Background="White" Grid.Row="2" Grid.ColumnSpan="3" ItemsSource="{x:Bind Errors}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical" ScrollViewer.VerticalScrollBarVisibility="Auto">
<TextBlock Foreground="Red" TextWrapping="Wrap" Text="{Binding}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

请指教。

文本块前景色设置为红色。我需要为不同的消息设置不同的颜色。

您可以使用IValueConverter接口来处理,使用转换器类将不同的消息类型转换为不同的SolidBrush用于文本块Foreground。您可以参考以下颜色转换器。

public class ColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (Boolean.Parse(value.ToString()))
{
return new SolidColorBrush(Colors.Green);
}
else
{
return new SolidColorBrush(Colors.Gray);
}
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}

用法

<Page.Resources>
<local:ColorConverter x:Key="Converter"/>
</Page.Resources>
......
<TextBlock Text="{Binding info}" Foreground="{Binding messageType,Converter={StaticResource Converter}}"/>