开发者

Setting the background color of separate WPF ListBox items

I want to set the background color separately for each item in a WPF ListBox. e.g.开发者_StackOverflow If I am adding Widgets to the ListBox, I might set the background color for each one based on the type of widget. This must be done in code (not XAML) as I only know what the items are at run time.

I know how to use ItemContainerStyle to set the style for all items, but how do you do it separately for each item?


Yes you do set ItemContainerStyle, using a StyleSelector.

This example at MSDN is exactly what you are looking for.


There are lots of ways to do this.

One is to use a StyleSelector, as loxxy suggests. This is pretty low on my list, because that kind of code is harder to read (well, find) and test than I'd like.

Another is to use a DataTrigger in the style. This is simple, if (and only if) the items all implement a common property that can be used in the trigger. You might be well served by implementing a wrapper class that exposes this common property, and contains the logic that figures out what value to assign to the property based on the object it's wrapping. (Whether or not this is easier than a StyleSelector is certainly arguable.)

If the items are really and truly heterogeneous, you can accomplish the result by using data templates, e.g.:

<ListBox.Resources>
   <DataTemplate DataType="{x:Type local:Foo}">
      <TextBlock Text="{Binding FooText}" Background="Red"/>
   </DataTemplate>
   <DataTemplate DataType="{x:Type local:Bar}">
      <TextBlock Text="{Binding BarText}" Background="Yellow"/>
   </DataTemplate>
   <DataTemplate DataType="{x:Type local:Baz}">
      <TextBlock Text="{Binding BazText}" Background="PapayaWhip"/>
   </DataTemplate>
</ListBox.Resources>

etc. This would generally be my first choice, but your question doesn't really explain enough about the circumstances to know if it's the right way to go or not.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜