Lauri Peltonen
Lauri Peltonen

Reputation: 1542

Concatenating binding data

I have the following piece of code for a column in a grid:

<dxg:GridColumn.CellTemplate>
<DataTemplate>
    <StackPanel>
        <Rectangle Width="40" Height="10" Stroke="{ Binding Value, StringFormat='{}#{0}'}" StrokeThickness="5" />
    </StackPanel>
</DataTemplate>                                    
</dxg:GridColumn.CellTemplate>

The column is bound to a property which has hex values such as:
- aaaaaa
- 123456

So I want to show a rectangle which has color based on the property.

As I've understood, I need to modify my hex values to: 1) include the # sign 2) add alpha channel. The '99' in the formatting is just to test if the thing works with any alpha value - it does not.

How could I get this to work? Thanks!

Upvotes: 1

Views: 71

Answers (1)

Abe Heidebrecht
Abe Heidebrecht

Reputation: 30498

In a Binding, the StringFormat property only works on properties of type String. As MSDN states:

A string that specifies how to format the binding if it displays the bound value as a string.

The easiest way to solve your problem is to write an IValueConverter. This converter will take your input value and return a SolidColorBrush.

For instance, if your hex values are strings, the converter's Convert method:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    var str = (string)value;
    var r = Byte.Parse(str.Substring(0, 2), NumberStyles.HexNumber);
    var g = Byte.Parse(str.Substring(2, 2), NumberStyles.HexNumber);
    var b = Byte.Parse(str.Substring(4, 2), NumberStyles.HexNumber);

    return new SolidColorBrush(Color.FromRgb(r, g, b));
}

Upvotes: 3

Related Questions