StevieV StevieV - 12 days ago 4
C# Question

Is there a way to override the color of all items in a list-box?

I am using WPF for a GUI design and my GUI contains a list-box. In a nutshell, I am trying to make all of the list-box's items the same foreground-color

#FF548E19
. I understand that the foreground color of each individual item entered into the list-box can be defined by the XAML property:

Foreground="#FF548E19"


Since I am actually using data-binding with a view-model that I've constructed, I can't simply go and set the
Foreground
property for each item because they are populated at run-time. As an alternative, I tried to set the
Foreground
property on the list-box itself. This did nothing, all of the items are still showing up with the color white.

Question

Is there a way to ensure that each binding item (the items populated into the list-box) gets the foreground color
#FF548E19
without manually changing the colors at run-time?

Update

One of the comments has asked how I actually populate my list-box with items. So here is the data-binding property that gets shoved into the list-box on property-changed.

/// <summary>
/// A list of the failure codes (per entry).
/// </summary>
public List<string> FailCodes
{
get
{
return this.failCodes;
}

set
{
this.failCodes = value;
this.OnPropertyChanged("FailCodes");
}
}


Additionally, here is the XAML property (includes how
ItemsSource
gets bound).

<ListBox x:Name="listBox_failCodes"
Grid.Row="0"
Margin="0" Background="{x:Null}"
HorizontalContentAlignment="Center"
BorderBrush="{x:Null}"
Foreground="#FF548E19"
ItemsSource="{Binding FailCodes}"/>

Answer

In your markup, use an item template (as suggested in the comments) with a static Foreground value:

<ListBox x:Name="listBox_failCodes"
     Grid.Row="0" 
     Margin="0" Background="{x:Null}" 
     HorizontalContentAlignment="Center"
     BorderBrush="{x:Null}" 
     ItemsSource="{Binding FailCodes}"/>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Foreground="#FF548E19" Text="{Binding}"></TextBlock>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

This will apply to every item bound to the list box

Comments