【发布时间】:2009-08-20 10:04:59
【问题描述】:
我有一个绑定到 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 充满了这些项目,我需要 color-code(更改 ListBoxItem 的 background color)列表,具体取决于LogMessage 项的 Severity 参数。
这是我现在在 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 的背景颜色没有改变。
【问题讨论】:
-
我的直觉是这与 {RelativeSource TemplatedParent} 有关。调试应用程序时是否在输出窗口中出现任何绑定错误?
-
没有绑定错误,但不幸的是你是对的,这与我试图引用的对象无关。奇怪的是,输出窗口中没有绑定错误。
标签: wpf xaml binding listbox styling