views:

3347

answers:

3

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?

+1  A: 

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.

Jab
+1  A: 

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"&gt;
    <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.

Robert Macnee
A: 

The way to do this is really easy. Watch the videos here. The do a neat demo of clicking a paint swatch to change the color on the wall in there windows app and they are doing exactly what you are talking about. I believe it is in either the 3rd or 4th video but if you are new to WPF they are all worth watching. These are videos that are from the WPF Bootcamp that MS held before Expression Blend was launched.

Ironsides