WPF: Binding a listviewitem's background colour to a hex String property of an object
Asked Answered
B

2

5

Hey. I have an object that has a string property called BackgroundColor. This string is the hexidecimal representation of a color. I cannot change this object.

I'm binding a collection of these objects to a listView. What I would like to do is bind the background of the listview's row to the BackgroundColor property of the object that is displayed in the row.

What is the best way to to this?

Barcellona answered 11/12, 2008 at 18:27 Comment(0)
C
2

I think using a IValueConverter is the appropriate solution. You could make a HexConverter that converts the string hex value to Color. That link should get you started.

Cleland answered 11/12, 2008 at 19:25 Comment(0)
Q
6

You'll want to use a Style to bind the Background of ListViewItem to the item for the row. The item is the default DataContext of the ListViewItem so this should be straightforward:

<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:sys="clr-namespace:System;assembly=mscorlib"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid.Resources>
        <x:Array x:Key="colors" Type="{x:Type sys:String}">
            <sys:String>Red</sys:String>
            <sys:String>Yellow</sys:String>
            <sys:String>#0000FF</sys:String>
        </x:Array>
    </Grid.Resources>
    <ListView ItemsSource="{StaticResource colors}">
        <ListView.Resources>
            <Style TargetType="{x:Type ListViewItem}">
                <Setter Property="Background" Value="{Binding .}"/>
            </Style>
        </ListView.Resources>
    </ListView>
</Grid>

Instead of binding to the whole item you'll bind to the BackgroundColor, but it should be similar to the above. You have have to use a converter with the binding to prefix a "#", this is the signal to the built-in BrushConverter to parse it as hex.

Quince answered 11/12, 2008 at 19:33 Comment(0)
C
2

I think using a IValueConverter is the appropriate solution. You could make a HexConverter that converts the string hex value to Color. That link should get you started.

Cleland answered 11/12, 2008 at 19:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.