Search code examples
windows-phone-7listboxwindows-phone-7.1foreground

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!


Solution

  • 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>