开发者

WPF DataTrigger/Setter with DateTime comparison

开发者 https://www.devze.com 2023-02-22 02:10 出处:网络
I\'m just wondering whether it\'s possible todo a DATETIME comparison with the WPF, ideally I\'d like to 开发者_JS百科colour my datagrid depending on it\'s relevance to the current date.Red for past f

I'm just wondering whether it's possible todo a DATETIME comparison with the WPF, ideally I'd like to 开发者_JS百科colour my datagrid depending on it's relevance to the current date. Red for past files, green for future. Thanks for any help!

<dg:DataGrid Name="files_datagrid" DataContext="{Binding Source={StaticResource filelist_provider}}"         
ItemsSource="{Binding}" CanUserAddRows="False" AutoGenerateColumns="False" Grid.Row="1"> 
<Style TargetType="{x:Type dg:DataGridRow}">    <Style.Triggers>        
        <DataTrigger Binding="{Binding Path=[filedate]}" Value=">TODAY">            
            <Setter Property="Background" Value="Green" />      
        </DataTrigger>  
    </Style.Triggers> 
</Style>


I think you're better off using a Value Converter.

Something like this:

[ValueConversion(typeof(DateTime), typeof(Brush))]
public class DateTimeToBrushConverter : IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
    var dateTime = (DateTime)value;
    if (dateTime.Date < DateTime.Now)
      return Brushes.Red;
    if (dateTime.Date > DateTime.Now)
      return Brushes.Green;

    return Brushes.Black;
  }

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

You could move the colours to be parameters to make it more generic if you feel like it.

Then apply like this:

<Style TargetType="{x:Type dg:DataGridRow}">
  <Setter Property="Background" 
          Value="{Binding Path=fileDate, 
            Converter={StaticResource dateTimeToBrushConverter}}" />
</Style>

Where dateTimeToBrushConverter is created in your resources.

0

精彩评论

暂无评论...
验证码 换一张
取 消