gpt4 book ai didi

c# - 绑定(bind)到 ListBox ItemTemplate 中的矩形?

转载 作者:太空宇宙 更新时间:2023-11-03 10:51:47 25 4
gpt4 key购买 nike

我有一个 ListBox,它对内容使用数据绑定(bind)(绑定(bind)到 ObservableCollection),并使用 ItemTemplate 进行布局。在 ItemTemplate 中,有一个显示日期的 TextBlock(来自 ObservableCollection)和一个彩色矩形。

我希望矩形的填充颜色根据日期发生变化(以指示年龄)。但是,由于 Rectangle 本身未绑定(bind)到日期(而且我不知道它怎么可能),我无法让 DataTrigger 改变填充颜色。

是否有另一种方法可以让数据绑定(bind)控制矩形颜色?

编辑:

根据要求,这是我的 ListBox ItemTemplate 的(简化)副本。现在,矩形的填充颜色是固定的,但我想将其更改为根据 targetstartdate 字段而变化。

<ListBox Name="listBox1" ItemsSource="{Binding Path=testList}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="1*" />
</Grid.ColumnDefinitions>
<Rectangle Fill="#FF009A00" Width="5" StrokeThickness="1" Margin="0,1,4,1"/>
<TextBlock Text="{Binding targetstartdate}" Margin="0,0,0,4" Foreground="#FF009A00" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

最佳答案

您可以将矩形的 FillStroke 属性绑定(bind)到日期。然后,使用 IValueConverter将日期转换为适当的颜色。

<Window.Resources>
<local:DateToBrushConverter x:Key="DateToBrushConverter" />
</Window.Resources>

<Rectangle Fill="{Binding targetstartdate,Converter={StaticResource DateToBrushConverter}}"
... />

Convert 方法应该返回一个 Brush 对象,它与 Rectangle.Fill 属性匹配。

public class DateToBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var date = value as DateTime?;
if (!date.HasValue)
return new SolidColorBrush(Colors.Transparent);
else if (!date.Value > DateTime.Today.AddDays(-1))
return new SolidColorBrush(Colors.Blue);
// etc
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}

关于c# - 绑定(bind)到 ListBox ItemTemplate 中的矩形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21172904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com