简体   繁体   中英

Silverlight “conditional” binding to a datagrid column?

I'm programmatically setting up my datagrid columns for my datagrid, then binding the grid to an observable collection.

A couple of my columns are bound to DateTime properties, however, if they're null values in the database, it's setting the DateTime properties to the min value due to DateTime being a non nullable type.

My binding is as follows for the aforementioned columns:

DataGridTextColumn scanned = new DataGridTextColumn();
scanned.Header = "Scanned";
scanned.Binding = new Binding("DateScanned");
dataGrid.Columns.Add(scanned);

"DateScanned" being the datetime property. Now, instead of those values displaying in the grid as "1/1/0001", I'd prefer it if they were blanked out. Herein lies my question.

Can I set this binding up to be conditional somehow and if the property value is "1/1/0001", display nothing?

使用值转换器将特定值转换为空白或其他任何您想要的值。

I think you should use Converter in order to convert from you ModelView to View the data in format you want. Have a look on this simple tutorial :

Converter in Silverlight

Regards.

Nevermind, found out about binding converters. Wrote a "MinDateConverter" that checks if it's the min date time. If it is, it returns blank, otherwise it returns the datetime.

public class MinDateConverter : IValueConverter
{
    public MinDateConverter()
    {
    }

    public virtual object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        DateTime dt = (DateTime)value;
        if (dt.Equals(DateTime.MinValue))
            return string.Empty;
        else
            return dt.ToShortDateString();
    }

    public virtual object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return value;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM