views:

2078

answers:

3

I'm unable to use data binding in the ItemContainerStyle for a ListBox in Silverlight 3. It works fine in WPF. This is contrived example to demonstrate my problem. What I really want to is bind to the IsSelected property, but I think that this example is easier to follow.

I have a ListBox that is bound to a ObservableCollection<Item> of Item objects:

public class Item {
  public String Name { get; }
  public Brush Color { get; }
}

Here is the relevant Silverlight XAML:

<ListBox x:Name="listBox" ItemsSource="{Binding .}">
  <ListBox.ItemContainerStyle>
    <Style TargetType="ListBoxItem">
      <Setter Property="Background" Value="{Binding Color}"/>
    </Style>
  </ListBox.ItemContainerStyle>
  <ListBox.ItemTemplate>
    <DataTemplate>
      <TextBlock Text="{Binding Name}"/>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

The same XAML can be used in WPF if TargetType="ListBoxItem" is replaced with TargetType="{x:Type ListBoxItem}".

The WPF application will display the items in the list box and set their background color according to the Color property of the Item object. However, the Silverlight application fails with and XamlParseException having the text AG_E_RUNTIME_MANAGED_UNKNOWN_ERROR. Being a stubborn guy I Have even tried to remove the XAML that fails and created my own style instead like this:

  Binding binding = new Binding("Color");
  Setter setter = new Setter(ListBoxItem.BackgroundProperty, binding);
  Style style = new Style(typeof(ListBoxItem));
  style.Setters.Add(setter);
  listBox.ItemContainerStyle = style;

If I try to run this I get an ArgumentException after my Silverlight control has initialized.

What am I doing wrong? How can I bind a property on the ItemContainerStyle to a property of the item?

A: 

Your Item class isn't complete enough to tell, but Color is a Brush type and not a Color type right? Since the background property you're trying to set requires a brush.

Graeme Bradbury
Sorry, I forgot to add types to the properties of Item. Property Color has type Brush. I didn't include all my code to avoid writing a wall of text. However, I have a working sample that does the right thing in WPF and fails in Silverlight.
Martin Liversage
+4  A: 

AFAIK Silverlight (even 3) does not support bindings on style setters. You'd have to do some custom logic to alter the background colour when each item is loaded--probably by getting its parent in the visual tree, which would be the container, and setting it there.

Ben M
A: 

I'm having a similar problem here, any workaround found ?

I have a ListBox of items that I'm trying to place in various cells of a grid (through ItemsPanelTemplate) and the only way I found to do this is to set Grid.Row and Grid.Column through style setters, but it fails with AG_E_RUNTIME_MANAGED_UNKNOWN_ERROR.

Alex Galie