Dan14021
Dan14021

Reputation: 659

Binding Hex value to Color in XAML

I have objects stored in a database that I am displaying in a GridView. I am binding each of their properties from the database. The color property is stored as a Hex value.

I am trying to bind this hex value using a converter function as shown below and just returning Red every time for now.

It seems to be working but it eventually returns the following error: The program '[5548] TranslatorService.Example.exe: Managed (v4.0.30319)' has exited with code -1073741189 (0xc000027b).

Can anyone tell me what I am doing wrong?

The code-behind:

public class StringToColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, String language)
    {
        return Colors.Red;
    }

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

The XAML:

 <Grid.Background>
                        <SolidColorBrush Color="{Binding Path=ColorHex, Converter={StaticResource ColorConverter}}" />
                    </Grid.Background>

Thank you

Upvotes: 2

Views: 3505

Answers (3)

Lance McCarthy
Lance McCarthy

Reputation: 1917

In your posted converter code, you are returning Color.Red, so no matter what value is, you'll get Red every time.

Upvotes: 0

Dan14021
Dan14021

Reputation: 659

The problem seems to be resolved after recompiling.

Upvotes: 0

Micha&#235;l Hompus
Micha&#235;l Hompus

Reputation: 3479

In my experience you need to assing a Brush, not a Color:

SolidColorBrush mySolidColorBrush = new SolidColorBrush();
mySolidColorBrush.Color = Color.FromArgb(255, 255, 0, 0);

or

mySolidColorBrush.Color = Color.Red;

Upvotes: 3

Related Questions