我有一个绑定到LogMessages的ObservableCollection的ListBox。
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将填充这些项,我需要根据项的Severity参数更改LogMessage (change a background of 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,是因为message的Severity参数的类型为Int (0..3),我们可以使用该参数轻松地在样式之间进行切换。
这个概念很清楚,但到目前为止,它对我还不起作用。ListBoxItem的背景色没有改变。
发布于 2009-08-20 10:38:48
使用ItemContainerStyle
<ListBox ItemsSource="{Binding LogMessages}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Background" Value="{Binding Severity, Converter={StaticResource YourBackgroundConverter}}"/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
发布于 2009-08-20 10:46:38
就像Bojan评论的那样,RelativeSource不应该出现在那里。在绑定到数据对象时使用{Binding Path=Severity,Converter={StaticResource BackgroundSeverityConverter}}。RelativeSource.TemplatedParent用于绑定到ListBoxItem。
另外,我有一点恼火,你可以考虑使用触发器,例如:
<Style x:Key="BindingAlternation" TargetType="{x:Type ListBoxItem}">
<Style.Triggers>
<DataTrigger Binding="{Binding Severity}" Value="1">
<Setter Property="Background" Value="Green"/>
</DataTrigger>
<DataTrigger Binding="{Binding Severity}" Value="2">
<Setter Property="Background" Value="Yellow"/>
</DataTrigger>
<!-- etc.. -->
</Style.Triggers>
<Style x:Key="BindingAlternation" TargetType="{x:Type ListBoxItem}">
但这只是一个个人preference....what,如果你修复了绑定,它应该可以正常工作。
https://stackoverflow.com/questions/1305157
复制相似问题