基于IList中项目中的数据的WPF数据绑定和样式 [英] WPF Databinding and Styling based on Data in an item in an IList

查看:146
本文介绍了基于IList中项目中的数据的WPF数据绑定和样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ListBox绑定到一个项目列表(为了争论,让我们说它有一个字符串和两个日期输入和完成)。

I have a ListBox bound to a list of Items (for arguement, lets say its got a string and two dates Entered and Done).

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

I would like to make the background color of items in the ListBox have a gray color if the Done DateTime is != DateTime.MinValue.

编辑:

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

Should I make a converter? and convert DateTime to a Brush based on the value of the DateTime?

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

Is something like this my best option? or is there a simple Xaml snippet I could use?

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


推荐答案

一个 ValueConverter 将工作。另一个选择是使用 ListBoxItem 的样式的 DataTrigger 。可能是这样的:

A ValueConverter would work. Another option would be to use a DataTrigger in the style of ListBoxItem. Maybe something like this:

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

完成不是 DateTime.MinValue 。我不认为有一种方法可以在触发器中进行不平等比较,因此默认情况下将背景设置为Gray,如果完成还没有改变使用正确的背景颜色可能会更好,而不是使用白色(可能获得父母背景的价值),但是这应该会给你一些开始。

This will set the background to Gray when the value of Done isn't DateTime.MinValue. I don't think there is a way to do a not equals comparison in a trigger, so it sets the background to Gray by default, and only changing it back to white if Done hasn't changed yet. It would probably be better to use the correct color for the background instead of white (maybe get the value of the parent's background?), but this should give you something to start with.

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

Update: To apply this style to the items of only certain ListBoxes, give the style a name and set the ItemContainerStyle as appropriate:

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

这篇关于基于IList中项目中的数据的WPF数据绑定和样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆