Search code examples
c#wpfxamlgridviewcolumn

Hide some values in XAML GridViewColumn if they met a condition


I have a GridView with some elements binded to my object. The value where I'm working is this:

<GridViewColumn x:Name="DataGridLastEdit" Header="Last Edit" Width="150px" DisplayMemberBinding="{Binding lastEdit}" />

lastEdit is a DateTime type, but for some elements its empty and it display 1/1/0001 12:00:00 AM (it can change based on computer time format setting), making a pretty ugly effect.

I just want to hide it for element who don't have a valid date, but I'm pretty new to XAML and I can't to that. I read about using Converters but I always do some errors writing it and can't even try if it works, how can I do that?


Solution

  • Use a ValueConverter:

    public class EmptyDateCoverter: IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if(value is DateTime)
            {
                if((DateTime)value == DateTime.MinValue)
                {
                     return "";
                }
            }
            return value;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            //We don't need convert back
            throw new NotImplementedException();
        }
    }
    

    Create a resource for the converter for example in the control's resources (conv is the alias for the namespace where the converter is defined )

    <conv:EmptyDateCoverter x:Key="EmptyDate" />
    

    and then apply the binding in this way:

    <GridViewColumn x:Name="DataGridLastEdit" Header="Last Edit" Width="150px" DisplayMemberBinding="{Binding lastEdit, Converter={StaticResource EmptyDate}}" />