'Changing the Background color of some ListBox Items

The ListBox is defined as follows:

 <ListBox x:Name="EditableStructs" Grid.Row="5" Grid.Column="1" Margin="930,62,0,40"  SelectionMode="Single"  Grid.ColumnSpan="2" Background="PowderBlue" Height="500"
                       ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.CanContentScroll="True"  ItemsSource="{Binding AutoNames,Mode=TwoWay}" HorizontalAlignment="Left" Width="220"  >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto"/>
                        <ColumnDefinition Width="Auto"/>
                        <ColumnDefinition Width="*"/>
                    </Grid.ColumnDefinitions>
                    <TextBlock Name="TextInd" Text="{Binding NamInd, Mode=OneWay}"  Grid.Column="0" Padding="1,5" HorizontalAlignment="Stretch"/>
                    <CheckBox IsChecked="{Binding IsAccepted, Mode=TwoWay}" Grid.Column="1"  Padding="5,5" VerticalAlignment="Center" HorizontalAlignment="Center"  />
                    <TextBox Text="{Binding  StrName, Mode=TwoWay}"  Background="{Binding MyBackground}"  Grid.Column="2" HorizontalAlignment="Stretch"/>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox> 

The number of items as well as which items should have a different colour is known at runtime when the strings to be displayed are being generated.

foreach (string str in EditedList)
        {
            AutoNames.Add(new EditableStructures { StrName = str,  IsAccepted = false, NamInd = j});
            j++;
        }

EditableStructs.ItemsSource = (System.Collections.IEnumerable)AutoNames;

Clearly indexing the ListBox makes sense after the ListBox has been generated. My problem is to select programmatically the ListBox items whose colour is to be changed: I tried the following:

 for(int i =0; i < EditableStructs.Items.Count; i++)
        {
            if (IsGuessed[i])
                EditableStructs.TextBox[i].Background = "Red";
        } 

But it does not work even if I replace TextBox with Items I would appreciate any kind of help. Thank you in advance

But it does not work even if I replace TextBox with Items

I would appreciate any kind of help. Thank you in advance



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source