user818700
user818700

Reputation:

Set listItem text color in C# code

I have a listBox, which obviously get filled up with list items through data binding. As you'll also probably know is that you specify what a listItem would look like with a listItem template tag like so:

<ListBox.ItemTemplate>
    <TextBlock Name="lblName" Text="{Binding Name}" Foreground="black" />
</ListBox.ItemTemplate>

Notice that the Foreground is black on the listItems Textbloxk...

Now in my C# code I'd like to dynamically set each listItems Textblock Foreground to which ever color I want. How does one reference a specific listItems Textblock and set the Foreground of it?

If any more info is needed, please ask! Thanks in advance!

Upvotes: 0

Views: 476

Answers (2)

Olivier Payen
Olivier Payen

Reputation: 15268

Do you really need to do it in the code-behind?

The preferred solution would be to bind the Foreground property to a ForegroundColor property of your ViewModel (if you use MVVM).

If you don't use MVVM and don't want to 'pollute' your model class with a Brush property, you could bind the Foreground property to a property you already have in your class (e.g Name or Age) and use a Converter to make it a Brush:

<ListBox.ItemTemplate>
    <TextBlock Name="lblName" Text="{Binding Name}" Foreground="{Binding Age, Converter={StaticResource AgeToColorConverter}}" />
</ListBox.ItemTemplate>

And the code of the converter:

public class AgeToColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // Your code that converts the value to a Brush
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Upvotes: 2

Igor Kulman
Igor Kulman

Reputation: 16361

A better and easier solution would be to add a property to your items of type SolidColorBrush representing the color, lets call id ForegroundColor and use a binding

<ListBox.ItemTemplate>
    <TextBlock Name="lblName" Text="{Binding Name}" Foreground="{Binding ForegroundColor}" />
</ListBox.ItemTemplate>

Upvotes: 1

Related Questions