通过绑定将ISO8061日期转换为EN-US

时间:2017-10-18 17:18:38

标签: c# wpf xaml mvvm

我正在尝试将我存储的ISO8061 DateTime(yyyy / MM / dd HH:mm:ss)转换为en-US短日期(MM / dd / yyyy),以便在我的数据网格中显示。我尝试在绑定时使用stringformat以及创建转换器来完成这项工作。

在下面的示例中:cal_date是通过SQLite数据库中的数据适配器填充的数据表列。

以下是该模型的片段:

    public DataTable RetrieveToolRoster()
    {
        string db_command = "SELECT [id], [description], [serial], [model], [manufacturer], [location], [cal_interval], " +
                            "[cal_date], [cal_due], [checked_out], [tool_lock] FROM inventory WHERE [cal_date] IS NOT NULL ORDER BY [id] ASC;";
        DataTable tr_dataTable = new DataTable();
        using (SQLiteConnection db_connection = new SQLiteConnection(Properties.Settings.Default.db_connectionstring))
        {
            using (SQLiteDataAdapter db_dataAdapter = new SQLiteDataAdapter(db_command, db_connection))
                try
                {
                    db_connection.Open();
                    db_dataAdapter.Fill(tr_dataTable);
                    db_connection.Close();
                    return tr_dataTable;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error:\r\n" + ex.Message);
                    return null;
                }
        }
    }

以下是我尝试过的一些例子。

尝试通过StringFormat进行格式化

Binding="{Binding cal_date, StringFormat=MM/dd/yyyy}"/>

Binding="{Binding cal_date, StringFormat='MM/dd/yyyy'}"/>

Binding="{Binding cal_date, StringFormat=d}"/>

Binding="{Binding cal_date, ConverterCulture='en-US', StringFormat=d}"/>

Binding="{Binding cal_date, StringFormat={}{0:MM/dd/yyyy}}"/>

Binding="{Binding cal_date, StringFormat='{}{0:MM/dd/yyyy}'}"/>

尝试通过转换器格式化:

XAML

<DataGridTextColumn Header="Calibration Date:"
                            Width="*"
                            Binding="{Binding cal_date, Converter={StaticResource ISOtoENUS}}"/>

C#

class ISO8061toENUSConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is string)
        {
            var dt = string.Format("{0:MM/dd/yyyy}", value);
            return dt;
        }
        return string.Empty;
    }

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

所有结果都一样,返回(yyyy / MM / dd HH:mm:ss)

我已经在这里待了差不多两天了。我搜索并搜索过。我甚至尝试过从他们让它工作的问题中实现代码片段,但无济于事。我做错了什么?

1 个答案:

答案 0 :(得分:1)

修改

如果CalDate是一个字符串,那么您可以使用DateTime.TryParse修改转换器:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    if (value is string)
    {
        DateTime parsedDate = DateTime.MinValue;
        if (DateTime.TryParse(value.ToString(), null, DateTimeStyles.RoundtripKind, out parsedDate))
        {
            return string.Format("{0:MM/dd/yyyy}", parsedDate);
        }
    }
    return string.Empty;
}

使用DateTime对象

我认为转换器方式是正确的,假设cal_date属性是DateTime对象:

private DateTime _calDate;
public DateTime CalDate
{
     get { return _calDate; }
     set
     {
         _calDate = value;
         NotifyPropertyChanged();
     }
 }

然后更改转换器以使用DateTime对象:

public class ISO8061toENUSConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is DateTime)
        {
            return string.Format("{0:MM/dd/yyyy}", value);
        }
        return string.Empty;
    }

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

这是我使用的绑定:

DataGridTextColumn Header="Calibration Date:"
                        Width="*"
                        Binding="{Binding CalDate, Mode=OneWay, Converter={StaticResource ISOtoENUS}}"/>

你应该得到正确的价值(我测试过并且对我有用)。