Angry Red Panda
Angry Red Panda

Reputation: 439

Change ListBox Item Background color programmatically

I am having a real hard time understanding how XAML works in connection to C#. My Problem is, that I have two different List<String> Objects filled with Content, I want one List<String> to have the backgroundcolor 'blue' and the other one to have the background color 'red'. Afterwards I want to display it in my ListBox

My XAML ListBox code:

<ListBox x:Name="ListBox1" HorizontalAlignment="Left" Height="240" Margin="81,80,0,0" VerticalAlignment="Top" Width="321" BorderBrush="#FF6C6C6C" SelectionMode="Single" SelectionChanged="ListBoxSelectionChanged">

</ListBox>

My C# Code that loads all the Content into the ListBox

public void AddItemsToListBox()
{
     foreach (var object1 in objects1)
     {
         //I want these Objects to be blue
         listBox1.Items.Add(object1.label);
     }
     foreach (var object2 in objects2)
     {
          //I want these Objects to be red
          listBox1.Items.Add(object2.label);
     }
 }

Upvotes: 3

Views: 6048

Answers (2)

Andrei Tătar
Andrei Tătar

Reputation: 8295

Here you go:

foreach (var object1 in objects1)
{
    Thread.Sleep(1);
    listBox1.Items.Add(new ListBoxItem { Content = object1.label, Background = Brushes.Blue });
 }
 foreach (var object2 in objects2)
 {
     Thread.Sleep(1);
     ListBox2.Items.Add(new ListBoxItem { Content = objects2.label, Background = Brushes.Red });
     //I want these Objects to be red
 }

A better way would be to use data binding, styles, etc.

Upvotes: 5

Sam
Sam

Reputation: 200

need 50 reputation to comment so added as an answer

why cant you just do it in xaml?

<ListBox x:Name="ListBox1" Background="Red">

</ListBox>

just add the background property, this will colour your list boxes

but if you want to become better at wpf i suggest learning DATABINDING so you dont need to manually add objects to the list box

and then after that take a look at MVVM

Upvotes: 0

Related Questions