首页 文章

绑定到ListBox ItemTemplate中的Rectangle?

提问于
浏览
2

我有一个ListBox,它使用内容的数据绑定(绑定到ObservableCollection),以及用于布局的ItemTemplate . 在ItemTemplate中,有一个显示日期的TextBlock(来自ObservableCollection)和一个彩色的Rectangle .

我希望矩形的填充颜色根据日期(表示年龄)而改变 . 但是,由于Rectangle本身并未绑定日期(我不知道它是怎么回事),我无法让DataTrigger工作来改变填充颜色 .

是否有另一种方法可以通过数据绑定控制Rectangle颜色?

Edit:

这是我的ListBox ItemTemplate的(简化)副本,如请求的那样 . 现在,Rectangle的填充是一种设置颜色,但我想根据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>

2 回答

  • 1

    您可以将矩形的 FillStroke 属性绑定到Date . 然后,使用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();
        }
    }
    
  • 1

    将矩形的颜色绑定到IValueConverter,使用日期作为绑定,并根据IValueConverter类中的日期确定颜色 .

相关问题