【问题标题】:WPF: Binding a listviewitem's background colour to a hex String property of an objectWPF:将listviewitem的背景颜色绑定到对象的十六进制字符串属性
【发布时间】:2010-09-26 11:58:10
【问题描述】:

嘿。我有一个对象,它有一个名为 BackgroundColor 的字符串属性。此字符串是颜色的十六进制表示。我无法更改此对象。

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

最好的方法是什么?

【问题讨论】:

    标签: wpf listview binding colors listviewitem


    【解决方案1】:

    您需要使用 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 将其解析为十六进制的信号。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-04-25
        • 2010-10-12
        • 1970-01-01
        • 1970-01-01
        • 2016-04-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多