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?