Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 729
Robin Avatar asked Dec 11 '08 18:12

Robin


2 Answers

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.

like image 126
Robert Macnee Avatar answered Oct 27 '22 01:10

Robert Macnee


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.

like image 43
Jab Avatar answered Oct 26 '22 23:10

Jab