问题描述
我有一个 ListBox,它绑定到 LogMessages 的 ObservableCollection.
I have a ListBox which is bound to ObservableCollection of LogMessages.
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 被这些项目填满,我需要颜色代码(更改 ListBoxItem 的背景颜色)列表取决于LogMessage 项的严重性参数.
ListBox is getting filled with those Items, and I need to color-code (change a background color of ListBoxItem) list depending on a Severity parameter of a LogMessage item.
这是我现在在显示日志的用户控件 XAML 中的内容:
Here's what I have now in XAML of user control showing the log:
<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 IsSynchronizedWithCurrentItem="True"
ItemTemplate="{DynamicResource LogDataTemplate}"
ItemsSource="{Binding LogFacility.LogMessages}"
x:Name="logListBox" Grid.Row="1"
ItemContainerStyle="{StaticResource BindingAlternation}" />
使用 AlternationConverter 是因为消息的 Severity 参数是 Int (0..3) 类型,我们可以使用该参数轻松切换样式.
The AlternationConverter is used because the Severity parameter of message is of type Int (0..3), and we can easily switch between styles using that one.
概念很清楚,但到目前为止它对我不起作用.ListBoxItem 的背景颜色没有改变.
The concept is clear, but so far it does not work for me. The Background color of ListBoxItem did not change.
推荐答案
使用ItemContainerStyle
:
<ListBox ItemsSource="{Binding LogMessages}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Background" Value="{Binding Severity, Converter={StaticResource YourBackgroundConverter}}"/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
这篇关于WPF、XAML:如何使用 ListBox ItemsSource 对象的属性绑定来设置 ListBoxItem 的样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!