本文介绍了WPF,XAML:如何使用对ListBox ItemsSource对象的属性进行绑定来设置ListBoxItem的样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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>();
}

每个消息都有两个参数:

Each Message has two parameters:

public class LogMessage
{
    public string Msg { get; set; }
    public int Severity { get; set; }
    //code cut...
}

ListBox充满了这些项,并且我需要根据列表进行颜色编码(更改 ListBoxItem 背景色)列表LogMessage项的 Severity 参数.

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:

and an actual ListBox:

<ListBox IsSynchronizedWithCurrentItem="True" 
    ItemTemplate="{DynamicResource LogDataTemplate}" 
    ItemsSource="{Binding LogFacility.LogMessages}" 
    x:Name="logListBox" Grid.Row="1" 
    ItemContainerStyle="{StaticResource BindingAlternation}" />

之所以使用AlternateConverter,是因为message的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的样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 23:21