在我的WPF应用程序中,我具有项目控件,该控件显示一周中的日期和星期几。 现在,我需要更改项目的背景颜色,即今天的日期。 这是XAML代码
<ItemsControl Grid.Column="1"
Focusable="False"
ItemsSource="{Binding WeekDays}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate >
<DataTemplate>
<Border BorderBrush="{StaticResource GrayBrush7}"
BorderThickness="1,0,0,0"
SnapsToDevicePixels="True"
UseLayoutRounding="True">
<StackPanel Margin="2"
VerticalAlignment="Center">
<TextBlock HorizontalAlignment="Center"
VerticalAlignment="Top"
Text="{Binding Day}"
TextAlignment="Center"/>
<TextBlock HorizontalAlignment="Center"
VerticalAlignment="Top"
Text="{Binding Date,
StringFormat='dd/MM/yyyy'}"
TextAlignment="Center"/>
</StackPanel>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
谢谢。
答案 0 :(得分:0)
如果模型类中具有n - size + 1
属性,则可以在Border Style中使用DataTrigger。像这样
IsToday
public class WeekDay
{
public DateTime Date { get; }
public string Day { get; }
public bool IsToday { get; }
public WeekDay(DateTime date)
{
this.Date = date;
this.Day = date.DayOfWeek.ToString();
this.IsToday = date.Date == DateTime.Today;
}
}
或者,您可以使用ValueConverter将Date转换为Background。
<ItemsControl.ItemTemplate >
<DataTemplate>
<Border BorderBrush="{StaticResource GrayBrush7}"
BorderThickness="1,0,0,0"
SnapsToDevicePixels="True"
UseLayoutRounding="True">
<Border.Style>
<Style TargetType="Border">
<Style.Triggers>
<DataTrigger Binding="{Binding IsToday}" Value="True">
<Setter Property="Background" Value="Yellow" />
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
...
public class DateToItemBackgroundConverter : IValueConverter
{
private static readonly Brush TodayBGBrush = new SolidColorBrush(Colors.Yellow);
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null || !(value is DateTime))
{
return value;
}
var isToday = ((DateTime)value).Date == DateTime.Today;
return isToday ? TodayBGBrush : null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
请记住,如果要在TODAY更新时刷新背景,则应重建模型数据或再次通知PropertyChanged。
答案 1 :(得分:0)
您可以在Border
中添加带有DataTrigger
的{{1}}样式。将您的ItemTemplate
属性的Date
属性与静态DateTime
属性进行比较:
DateTime.Today