Reputation: 106796
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?
Upvotes: 3
Views: 4194
Reputation: 22492
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.
Upvotes: 5
Reputation: 3721
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.
Upvotes: 0