【问题标题】:WPF Databinding and Styling based on Data in an item in an IList基于 IList 中项目中的数据的 WPF 数据绑定和样式
【发布时间】:2010-04-19 01:16:14
【问题描述】:

我有一个 ListBox 绑定到一个项目列表(为了争论,假设它有一个字符串和两个日期 Entered 和 Done)。

如果 Done DateTime 为 != DateTime.MinValue,我想让 ListBox 中项目的背景颜色为灰色。

编辑:

我应该做一个转换器吗?并根据 DateTime 的值将 DateTime 转换为 Brush?

这样的事情是我最好的选择吗?还是有一个简单的 Xaml sn-p 我可以使用?

[ValueConversion(typeof(DateTime), typeof(Brush))]
class MyConverter : IValueConverter
{
    ...
}

【问题讨论】:

    标签: c# .net wpf data-binding


    【解决方案1】:

    ValueConverter 可以。另一种选择是以ListBoxItem 的样式使用DataTrigger。也许是这样的:

    <Style x:Name="MinDateTimeListBoxStyle" TargetType="ListBoxItem">
        <Style.Triggers>
            <Setter Property="Background" Value="Gray" />
            <DataTrigger Binding="{Binding Path=Done}"
                Value="{x:Static sys:DateTime.MinValue}">
                <Setter Property="Background" Value="White" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
    

    Done 的值不是DateTime.MinValue 时,这会将背景设置为灰色。我认为没有办法在触发器中进行不等于比较,因此默认情况下它将背景设置为灰色,并且只有在 Done 尚未更改时才将其更改回白色。为背景使用正确的颜色而不是白色可能会更好(也许得到父背景的值?),但这应该给你一些开始。

    更新:要将此样式仅应用于某些列表框的项目,请为样式命名并根据需要设置ItemContainerStyle

    <ListBox x:Name="StyledListBox"
        ItemContainerStyle="{StaticResource MinDateTimeListBoxStyle}" />
    <ListBox x:Name="NormalListBox" />
    

    【讨论】:

    • 我刚刚发布了这个相同的解决方案,然后删除了它,因为我看到你打败了我......我 1 up'd yours :D
    • 这行得通,但它会影响我窗口上的每个 ListBox - 我怎样才能使它仅适用于单个 ListBox?
    猜你喜欢
    • 1970-01-01
    • 2010-10-30
    • 2012-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-24
    • 2019-10-18
    相关资源
    最近更新 更多