Reputation: 25
I have a project in which I have in my main window a listbox of columns and inside of it I have a listbox of tasks for each column. I need to change the border color of each task on some condition : i.e if 75% of the time has passed since we created the task it will be colored orange , red if overdue and so on. how can i change a specific task in my listbox with binding ? I don't understand how to get the task details because it needs to happen instantly and not only if the task is selected. any ideas ?
Upvotes: 0
Views: 575
Reputation: 3038
Use a ValueConverter. While I don't know exactly what you mean by "75% of time has passed since we created the task", I will assume you mean as a deadline approaches.
Example:
public class DueTimeColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var dueTime = (DateTime)value;
if (dueTime.Date >= DateTime.Now)
return new SolidColorBrush(Colors.Red);
else if (TimeSpan.FromTicks(DateTime.Now.Ticks - dueTime.Date.Ticks).TotalDays <= 2)
return new SolidColorBrush(Colors.Orange);
return new SolidColorBrush(Colors.Green);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Then use it in your XAML by applying the value converter to your binding of the border color, based on the task's due date:
<ListBox ItemsSource="{Binding Items}" HorizontalContentAlignment="Stretch">
<ListBox.Resources>
<local:DueTimeColorConverter x:Key="colorConverter"/>
</ListBox.Resources>
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderThickness="1">
<TextBlock Text="{Binding Name}" Margin="5"/>
<Border.Style>
<Style TargetType="Border">
<Setter Property="BorderBrush" Value="{Binding DueTime, Converter={StaticResource colorConverter}}"/>
</Style>
</Border.Style>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
My simplified "Item" class and its ObservableCollection:
this.Items.Add(new Item() { Name = "Item 1", DueTime = DateTime.Today.AddDays(-7) });
this.Items.Add(new Item() { Name = "Item 2", DueTime = DateTime.Today.AddDays(-6) });
this.Items.Add(new Item() { Name = "Item 3", DueTime = DateTime.Today.AddDays(-5) });
this.Items.Add(new Item() { Name = "Item 4", DueTime = DateTime.Today.AddDays(-4) });
this.Items.Add(new Item() { Name = "Item 5", DueTime = DateTime.Today.AddDays(-3) });
this.Items.Add(new Item() { Name = "Item 6", DueTime = DateTime.Today.AddDays(-2) });
this.Items.Add(new Item() { Name = "Item 7", DueTime = DateTime.Today.AddDays(-1) });
this.Items.Add(new Item() { Name = "Item 8", DueTime = DateTime.Today });
this.Items.Add(new Item() { Name = "Item 9", DueTime = DateTime.Today.AddDays(1) });
this.Items.Add(new Item() { Name = "Item 10", DueTime = DateTime.Today.AddDays(2) });
this.Items.Add(new Item() { Name = "Item 11", DueTime = DateTime.Today.AddDays(3) });
Example output:
Upvotes: 1