RSS
 

Listbox Individual Item Color in Silverlight

12 Jul

This post is mainly a reply on this StackOverflow Question: how to change listbox item’s color individually programmatically in silverlight?

We want to modify the Listbox item template so we get the following layout:

The implementation is fairly simple. We use a converter on our Listbox Item binding and return a Style Property.

The Message Model implementation:

public class Message
    {
        public string Name { get; set; }
        public bool IsInError { get { return String.IsNullOrEmpty(ErrorMessage); } }
        public string ErrorMessage { get; set; }
    }

In the listbox, we will bind these message properties for each item. We can have a different style based on these properties by using the listbox ItemTemplate.
The Listbox Item Template implementation:

        
            
                
                        
                
            
        

For each listbox item, we will assign a style for our TextBlock element.
The Converter implementation:

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if ((bool)value)
            {
                return Application.Current.Resources["ListBoxTextNormalItem"];
            }

            return Application.Current.Resources["ListBoxTextErrorItem"];
        }

The Style implementation:

        

        

You can download the sample source here: ListBoxItemColorSample

 
 

Leave a Reply