Home > Mobile >  WPF Trigger based on DataGridCell Value Type
WPF Trigger based on DataGridCell Value Type

Time:10-01

What i am trying is

<local:class_converter_data_type x:Key="DataTypeConverter"/>
 <Style TargetType="{x:Type DataGridCell}">
     <Style.Triggers>
         <DataTrigger Binding="{Binding RelativeSource={x:Static RelativeSource.Self}, Converter={StaticResource DataTypeConverter}}" Value="{x:Type sys:DateTime}">
             <Setter Property="FontStyle" Value="Italic" />
         </DataTrigger>
   </Style.Triggers>
</Style>
       
 public class class_converter_data_type : IValueConverter
  {
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
       {
           return value?.GetType() ?? Binding.DoNothing;
       }
 
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
          throw new NotImplementedException();
         }
   }

What errors i am making here? Binding format has any errors or in conversion?

CodePudding user response:

You should not do it like this. The DataGridCell does not directly contain any type information of the underlying data type. The cleanest way is to listen to the DataGrid.AutoGeneratingColumn event and configure the appearance of the column's content:

MainWindow.xaml

<DataGrid AutoGeneratingColumn="DataGrid_AutoGeneratingColumn" />

MainWIndow.xaml.cs

private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
  var dataGrid = sender as DataGrid;
  if (e.PropertyType.Equals(typeof(DateTime)) 
    && e.Column is DataGridTextColumn column)
  {
    column.FontStyle = FontStyles.Italic;
  }
}

In case you are not auto-generating the columns, you can set the font style by setting the DataGridTextColumn.FontStyle XAML attribute.

<DataGrid>
  <DataGrid.Columns>
    <DataGridTextColumn FontStyle="Italic" />
  </DataGrid.Columns>
</DataGrid>
  • Related