Question

I am trying to change the foreground color of my databinded TextBlock in ListBox depending on binding value.

My code is give below: xaml

<Grid.Resources>
   <converters:ColorConverter x:Key="ColorConverter"/>
</Grid.Resources>


<ListBox>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Name="TitleText">
                <Run Foreground="{Binding Type, Converter={StaticResource ColorConverter}}" Text="&#x20b9;" />
            </TextBlock>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

ColorConverter class:

public class ColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value != null)
        {
             String Value = (String)value;

             if (Value.Equals("Credit"))
                return Colors.Green;
            else
                return Colors.Red;

        }

        return null;
    }

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

When i run the code, there are no errors but colors wont change.

Was it helpful?

Solution

Foreground takes a brush, not a color. Try this:

<Run Text="...">
    <Run.Foreground>
        <SolidColorBrush Color="{Binding Type, Converter={StaticResource ColorConverter}}"/>
    </Run.Foreground>
</Run>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top