user1108948
user1108948

Reputation:

Dynamically change the color of listbox items in code behind(WPF)

I have a traffic application. The light status is updated in the listbox.

<ListBox x:Name="lbxCallProgress"  ItemsSource="{Binding Messages,Mode=TwoWay}" Height="373" FontSize="8" ScrollViewer.VerticalScrollBarVisibility="Visible">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

For the Messages:

public partial class MainWindow : Window
{
    public ObservableCollection<string> Messages { get; set; }

To update messages to the listbox.

    void UpdateMessage(string message)
    {
        try
        {
            Dispatcher.BeginInvoke((Action)delegate()
            {
                Dispatcher.BeginInvoke(new Action(() => { this.Messages.Add(message); }));
            });
        }

Now if the string message contains the keyword "green", then I want to set the item color on the listbox as color green, etc.

How?

Upvotes: 0

Views: 2128

Answers (1)

pushpraj
pushpraj

Reputation: 13669

here you go

with the power of WPF binding you can use the value to bind to the desired property Background and the implicit converter will do the rest for you.

    <DataTemplate>
        <TextBlock Text="{Binding}" Background="{Binding}"/>
    </DataTemplate>

you can choose to bind Foreground in case if you want to change the text color


Using converters

if simple binding is not sufficient enough you may use converters to perform custom logic of conversion, eg converting The light is red to Brushes.Red

public class MyColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string text = value as string;

        if(text.Contains("red"))
           return Brushes.Red;

        return Brushes.White;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return DependencyProperty.UnsetValue;
    }
}

usage

<DataTemplate xmlns:l="your namespace to converter class">
    <DataTemplate.Resources>
        <l:MyColorConverter x:Key="MyColorConverter" />
    </DataTemplate.Resources>
    <TextBlock Text="{Binding}" Background="{Binding Converter={StaticResource MyColorConverter}}"/>
</DataTemplate>

Upvotes: 2

Related Questions