我有一个ListBox,它绑定了LogMessages的ObservableCollection。
public ObservableCollection<LogMessage> LogMessages { get; set; }
public LogMessageData()
{
this.LogMessages = new ObservableCollection<LogMessage>();
}
每个消息都有两个参数:public class LogMessage
{
public string Msg { get; set; }
public int Severity { get; set; }
//code cut...
}
ListBox正在填充这些项,我需要根据LogMessage项目的Severity参数对列表进行颜色编码(更改 ListBoxItem的背景颜色 )。
这是我现在在XAML中显示日志的用户控件:
<UserControl.Resources>
<AlternationConverter x:Key="BackgroundSeverityConverter">
<SolidColorBrush>Green</SolidColorBrush>
<SolidColorBrush>Yellow</SolidColorBrush>
<SolidColorBrush>Red</SolidColorBrush>
</AlternationConverter>
<Style x:Key="BindingAlternation" TargetType="{x:Type ListBoxItem}">
<Setter Property="Background"
Value="{Binding RelativeSource={RelativeSource TemplatedParent},
Path=Severity,
Converter={StaticResource BackgroundSeverityConverter}}"/>
</Style>
<DataTemplate x:Key="LogDataTemplate">
<TextBlock x:Name="logItemTextBlock" Width="Auto" Height="Auto"
Text="{Binding Msg}"/>
</DataTemplate>
</UserControl.Resources>
和一个实际的ListBox:
<ListBox IsSynchronizedWithCurrentItem="True"
ItemTemplate="{DynamicResource LogDataTemplate}"
ItemsSource="{Binding LogFacility.LogMessages}"
x:Name="logListBox" Grid.Row="1"
ItemContainerStyle="{StaticResource BindingAlternation}" />
使用AlternationConverter是因为消息的Severity参数是Int类型(0..3),通过使用该参数,我们可以轻松地在各种样式之间切换。
概念很清楚,但直到现在它对我没有用。 ListBoxItem的背景颜色没有改变。