WPF:将listviewitem的背景颜色绑定到对象的十六进制String属性

时间:2008-12-11 18:27:28

标签: wpf listview binding colors listviewitem

嘿。我有一个具有名为BackgroundColor的字符串属性的对象。该字符串是颜色的十六进制表示。我无法改变这个对象。

我将这些对象的集合绑定到listView。我想要做的是将listview行的背景绑定到行中显示的对象的BackgroundColor属性。

最好的方法是什么?

2 个答案:

答案 0 :(得分:6)

您需要使用Style将ListViewItem的背景绑定到该行的项目。该项是ListViewItem的默认DataContext,因此这应该是直截了当的:

<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>

不是绑定到整个项目,而是绑定到BackgroundColor,但它应该与上面类似。您必须使用带有绑定的转换器作为前缀“#”,这是内置BrushConverter将其解析为十六进制的信号。

答案 1 :(得分:2)

我认为使用IValueConverter是合适的解决方案。您可以创建一个将字符串十六进制值转换为Color的HexConverter。该链接应该让你开始。