这可能是一个简单的答案,但我只是格式化数据形式字段的日期有问题。
<df:DataForm x:Name="Form1" ItemsSource="{Binding Mode=OneWay}" AutoGenerateFields="True"
AutoEdit="True" AutoCommit="False"
CommitButtonContent="Save"
CancelButtonContent="Cancel"
CommandButtonsVisibility="Commit"
LabelPosition="Top" ScrollViewer.VerticalScrollBarVisibility="Disabled"
EditEnded="NoteForm_EditEnded">
<df:DataForm.EditTemplate>
<DataTemplate>
<StackPanel>
<df:DataField>
<TextBox Text="{Binding Title, Mode=TwoWay}"/>
</df:DataField>
<df:DataField>
<TextBox Text="{Binding Description, Mode=TwoWay}" AcceptsReturn="True" HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Auto" Height="" TextWrapping="Wrap" SizeChanged="TextBox_SizeChanged"/>
</df:DataField>
<df:DataField>
<TextBlock Text="{Binding Username}"/>
</df:DataField>
<df:DataField>
<TextBlock Text="{Binding DateCreated}"/>
</df:DataField>
</StackPanel>
</DataTemplate>
</df:DataForm.EditTemplate>
</df:DataForm>
我已将此绑定到一个注释类,该注释类具有DateCreated字段的注释:
/// <summary>
/// Gets or sets the date created of the noteannotation
/// </summary>
[Display(Name="Date Created")]
[Editable(false)]
[DisplayFormat(DataFormatString = "{0:u}", ApplyFormatInEditMode = true)]
public DateTime DateCreated { get; set; }
无论我设置dataformatstring,它都会返回:例如4/6/2010 10:02:15 AM
我希望格式化为yyyy-MM-dd HH:mm:ss
我已经尝试了{0:yyyy-MM-dd hh:mm:ss}之上的自定义格式,但它仍保持相同的输出。对于{0:u}或{0:s}也是如此。
答案 0 :(得分:4)
通过在数据绑定中添加转换器来解决这个问题:
<df:DataField>
<TextBlock Text="{Binding DateCreated, Converter={StaticResource DateConverter}}"/>
</df:DataField>
DateConverter只是一个实现IValueConverter接口的类。以下示例显示了我需要的日期时间格式..
/// <summary>
/// Date time formatter - for short dates for data bound items
/// </summary>
public class DateConverter : IValueConverter
{
#region Public Methods
#region IValueConvertor Members
/// <summary>
/// Convert data item to a short date
/// </summary>
/// <param name="value">Value</param>
/// <param name="targetType">Target type</param>
/// <param name="parameter">Paramter</param>
/// <param name="culture">Culture</param>
/// <returns>Converted object</returns>
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var date = (DateTime)value;
return (date.ToString("dd/MM/yyyy HH:mm:ss"));
}
/// <summary>
/// Convert back data item to a short date
/// </summary>
/// <param name="value">Value</param>
/// <param name="targetType">Target type</param>
/// <param name="parameter">Paramter</param>
/// <param name="culture">Culture</param>
/// <returns>Converted object</returns>
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var s = (string)value;
return (DateTime.Parse(s));
}
#endregion IValueConvertor Members
#endregion Public Methods
}
这就像一种享受 - 可以通过一些空检查来改进! :)