基于IList中项目中的数据的WPF数据绑定和样式

Nat*_*ate 1 .net c# data-binding wpf

我有一个ListBox绑定到一个Items列表(对于争论,让我们说它有一个字符串和两个日期输入和完成).

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

编辑:

我应该制作转换器吗?并根据DateTime的值将DateTime转换为Brush?

这样的事情是我最好的选择吗?或者我可以使用一个简单的Xaml片段吗?

[ValueConversion(typeof(DateTime), typeof(Brush))]
class MyConverter : IValueConverter
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

And*_*ndy 8

A ValueConverter会工作的.另一种选择是使用DataTrigger风格的ListBoxItem.也许是这样的:

<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>
Run Code Online (Sandbox Code Playgroud)

当值Done不是时,这会将背景设置为灰色DateTime.MinValue.我不认为有一种方法可以在触发器中进行不等于比较,因此默认情况下将背景设置为灰色,如果Done尚未更改,则仅将其更改为白色.使用背景的正确颜色而不是白色可能会更好(可能得到父背景的值?),但这应该给你一些东西.

更新:要将此样式应用于仅某些ListBox的项目,请为该样式指定名称并ItemContainerStyle根据需要进行设置:

<ListBox x:Name="StyledListBox"
    ItemContainerStyle="{StaticResource MinDateTimeListBoxStyle}" />
<ListBox x:Name="NormalListBox" />
Run Code Online (Sandbox Code Playgroud)