我有一个来自WPF工具包的Accordion,其中我绑定了值
<layoutToolkit:Accordion x:Name="myAccordion">
<layoutToolkit:Accordion.ItemTemplate>
<DataTemplate>
<TextBlock x:Name="myHeader" Text="{Binding Date}" />
<DataTemplate.Resources>
<local:BeforeTodayConverter x:Key="IsBeforeToday" />
</DataTemplate.Resources>
<DataTemplate.Triggers>
<DataTrigger
Binding="{Binding Date, Converter={StaticResource IsBeforeToday}}"
Value="True">
<Setter
TargetName="myHeader"
Property="Foreground"
Value="Blue" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</layoutToolkit:Accordion.ItemTemplate>
<layoutToolkit:Accordion.ContentTemplate>
<DataTemplate>
//not important
</DataTemplate>
</layoutToolkit:Accordion.ContentTemplate>
</layoutToolkit:Accordion>
转换器:
public class BeforeTodayConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!(value is DateTime))
{
return false;
}
return ((DateTime)value).CompareTo(DateTime.Today) < 0;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
} 我想要的是改变文本块的前景&#34; myHeader&#34;取决于约束日期。如果日期是从今天开始的日期,我希望它是蓝色的,如果日期是从今天开始的日期,我希望它是红色的。
有没有办法解决这个问题?
答案 0 :(得分:1)
写一个值转换器来比较日期:
public class BeforeTodayConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!(value is DateTime))
{
return false;
}
return ((DateTime)value).CompareTo(DateTime.Today) < 0;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
并在模板中使用它:
<DataTemplate>
<TextBlock
x:Name="myHeader"
Text="{Binding Date}"
Foreground="Red"
/>
<DataTemplate.Resources>
<local:BeforeTodayConverter x:Key="IsBeforeToday" />
</DataTemplate.Resources>
<DataTemplate.Triggers>
<DataTrigger
Binding="{Binding Date, Converter={StaticResource IsBeforeToday}}"
Value="True"
>
<Setter
TargetName="myHeader"
Property="Foreground"
Value="Blue"
/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>