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

Rob*_*bin 5 wpf binding listview colors listviewitem

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

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

最好的方法是什么?

Rob*_*nee 6

您将要使用Style将ListViewItem的Background绑定到该行的项目.该项是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>
Run Code Online (Sandbox Code Playgroud)

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


Jab*_*Jab 2

我认为使用IValueConverter是合适的解决方案。您可以制作一个 HexConverter 将字符串十六进制值转换为颜色。该链接应该可以帮助您入门。