Reputation: 23
I have something like this:
public class Member {
public int Id { get; set; }
public string Name { get; set; }
public string Age { get; set; }
...
}
List<Member> members = new List<Member>{ new Member(Id = 1, Name="Chuck", Age="32"), new Member(Id = 2, Name="Eve", Age="10")};
Listbox1.ItemsSource = members;
How can I change the background of items in the ListBox
, if the age is less than 18?
Upvotes: 0
Views: 1367
Reputation: 22119
Setting the background of a ListBoxItem
can be done by changing the item container style. Conditional setting of the color however requires a IValueConverter
. You can write your own for checking Age
. Please consider making Age
a property of type int
, otherwise you will have to parse it on each conversion from string
.
public class AgeToColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return int.Parse((string)value) < 18 ? new SolidColorBrush(Colors.Red) : new SolidColorBrush(Colors.Blue);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new InvalidOperationException("This is a one-way conversion.");
}
}
In XAML you would create an instance of your converter in the resouces of the list box or any other resource dictionary. Then you would bind the ItemsSource
to your members
property and add a custom items container style. The style is based on the default style for the ListBoxItem
. In it you bind the Background
property to Age
with your custom converter, which will convert the age string to a solid color brush.
<ListBox x:Name="Listbox1" ItemsSource="{Binding members}">
<ListBox.Resources>
<local:AgeToColorConverter x:Key="AgeToColorConverter"/>
</ListBox.Resources>
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource {x:Type ListBoxItem}}">
<Setter Property="Background" Value="{Binding Age, Converter={StaticResource AgeToColorConverter}}"/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
Suppose you defined your list box in XAML like this.
<ListBox x:Name="Listbox1"/>
Then the same as for the XAML solution applies to this code, except for we create the converter as a local variable and the items source is directly assigned instead of a binding.
var ageToColorConverter = new AgeToColorConverter();
var baseItemContainerStyle = (Style)FindResource(typeof(ListBoxItem));
var itemContainerStyle = new Style(typeof(ListBoxItem), baseItemContainerStyle);
var backgroundSetter = new Setter(BackgroundProperty, new Binding("Age") { Converter = ageToColorConverter });
itemContainerStyle.Setters.Add(backgroundSetter);
Listbox1.ItemContainerStyle = itemContainerStyle;
Listbox1.ItemsSource = members;
Upvotes: 1