2

如何动态设置列表框中项目的背景颜色?即我的业务对象上也有一些属性,我也正在绑定,所以基于一些业务规则,我希望背景颜色不同?

        <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>

编辑:这里说

在 Silverlight 中,您必须将 x:Key 属性添加到您的自定义样式并将它们作为静态资源引用。Silverlight 不支持使用 TargetType 属性值应用的隐式样式。

这会影响我的方法吗?

4

4 回答 4

2

Ok - if you need custom logic to determine the background then I would look into building a simple IValueConverter class. You just need to implement the IValueConverter interface and, in its Convert method, change the supplied value into a Brush.

Here's a quick post from Sahil Malik that describes IValueConverters - it might help:

http://blah.winsmarts.com/2007-3-WPF__DataBinding_to_Calculated_Values--The_IValueConverter_interface.aspx

于 2008-09-30T10:02:25.287 回答
1

To bind your background to more than one property, you can use IMultiValueConverter. It's just like IValueConverter except that it works with MultiBinding to pass more than one value into a class and get back a single value.

Here's a post I found with a run-through on IMultiValueConverter and MultiBinding:

http://blog.paranoidferret.com/index.php/2008/07/21/wpf-tutorial-using-multibindings/

Edit: If IMultiValueConverter isn't available (it looks like Silverlight only has IValueConverter) then you can always pass your entire bound object (eg your Person object) to an IValueConverter and use various properties from that to return your Brush.

于 2008-09-30T10:18:52.627 回答
0

@Matt 感谢您的回复。我会调查触发器。

我唯一的问题是,确定一行是否应该着色的逻辑稍微复杂一些,所以我不能只检查一个属性,所以我实际上需要运行一些逻辑来确定颜色。有任何想法吗?

我想我可以用我需要的所有相关字段制作一个 UI 对象,但我有点不想采用这种方法。

于 2008-09-30T09:55:19.627 回答
0

您可以尝试将控件模板中的某些内容(即边框或​​其他内容)绑定到 TemplateBackground。然后在您的列表框上设置背景以确定它的颜色。

<Border Margin="-2,-2,-2,0" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="1,1,1,0" CornerRadius="11,11,0,0">
于 2009-07-14T01:37:56.630 回答