动态设置Silverlight控件的背景色(列表框)
如何动态设置列表框中项目的背景色?即我的业务对象上也有一些我要绑定的属性,因此基于某些业务规则,我希望背景颜色有所不同吗?
<ListBox Background="Red"> <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="Background" Value="Red"/> </Style> </ListBox.ItemContainerStyle> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal" Margin="5"> <TextBlock VerticalAlignment="Bottom" FontFamily="Comic Sans MS" FontSize="12" Width="70" Text="{Binding Name}" /> <TextBlock VerticalAlignment="Bottom" FontFamily="Comic Sans MS" FontSize="12" Width="70" Text="{Binding Age}" /> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox>
编辑:它说这里
In Silverlight, you must add x:Key attributes to your custom styles and reference them as static resources. Silverlight does not support implicit styles applied using the TargetType attribute value.
这会影响我的方法吗?
解决方案
@Matt感谢回复。我将研究触发器。
我唯一的问题是,确定行是否应该着色的逻辑稍微复杂一些,因此我不能仅检查属性,因此实际上我需要运行一些逻辑来确定颜色。有任何想法吗?
我想我可以用我需要的所有相关字段制作一个UI对象,但是我有点不想采用这种方法。
好吧,如果我们需要自定义逻辑来确定背景,那么我将考虑构建一个简单的IValueConverter类。我们只需要实现IValueConverter接口,并在其Convert方法中将提供的值更改为Brush。
这是Sahil Malik的快速文章,描述了可能有用的IValueConverters:
http://blah.winsmarts.com/2007-3-WPF__DataBinding_to_Calculated_Values--The_IValueConverter_interface.aspx
要将背景绑定到多个属性,可以使用IMultiValueConverter。就像IValueConverter一样,除了它与MultiBinding配合使用以外,它还可以将多个值传递给一个类并返回一个值。
这是我发现的有关IMultiValueConverter和MultiBinding的贯穿式帖子:
http://blog.paranoidferret.com/index.php/2008/07/21/wpf-tutorial-using-multibindings/
编辑:如果IMultiValueConverter不可用(看起来Silverlight仅具有IValueConverter),则我们始终可以将整个绑定对象(例如,Person对象)传递给IValueConverter,并使用该属性中的各种属性来返回Brush。
我们可以尝试将控件模板中的某些内容(例如边框或者其他内容)绑定到TemplateBackground。然后在列表框上设置背景以确定其颜色。
<Border Margin="-2,-2,-2,0" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="1,1,1,0" CornerRadius="11,11,0,0">