如何使DateTime属性绑定的TextBox在wpf c#中读取dd-mm-yyyy格式的日期

本文关键字:读取 dd-mm-yyyy 日期 格式 wpf DateTime 何使 属性 绑定 TextBox | 更新日期: 2023-09-27 17:59:19

我在WPF中有一个绑定到DateTime属性的TextBox。每当用户在该TextBox中输入日期时,我都需要绑定的DateTime属性来读取dd-MM-yyyy格式的日期。

即当用户输入05-04-2015时,绑定的DateTime属性应得到对应于2015年4月5日的DateTime值。

我做了一个正常的绑定,但物业将日期解释为2015年5月4日,而不是2015年4月5日。

视图中:

<TextBox Grid.Row="1" Grid.Column="1" Style="{StaticResource TextBoxStyle}" 
     Text="{Binding NewStaff.Insurance.ExpiryDate}"></TextBox>

在视图模型中,我有一个NewStaff属性,它引用了一个Staff类实例,这个Staff类有一个保险类实例。在保险类中,我有一个名为ExpiryDate的DateTime属性。

class Staff{
    public ICard Insurance{get;set;}
    public Staff(){
        Insurance = new Insurance();
    }
}
class Insurance:ICard
{
    /// <summary>
    /// Expiry date of insurance card.
    /// </summary>
    public DateTime ExpiryDate
    {
        get;
        set;
    }
 }

现在,当我在文本框中键入05-04-2015时,绑定的ExpiryDate属性将日期解释为2015年5月4日。鉴于我需要ExpiryDate将其解释为2015年4月5日。

如何使DateTime属性绑定的TextBox在wpf c#中读取dd-mm-yyyy格式的日期

您应该在数据绑定属性setter或IValueConverter.Convert方法中使用DateTime.ParseExact方法。这将使您能够使用所需的格式解析正确的DateTime值。请参阅MSDN上链接页面上的此示例:

  string dateString, format;  
  DateTime result;
  CultureInfo provider = CultureInfo.InvariantCulture;
  // Parse date-only value with invariant culture.
  dateString = "06/15/2008";
  format = "d";
  try {
     result = DateTime.ParseExact(dateString, format, provider);
     Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
  }
  catch (FormatException) {
     Console.WriteLine("{0} is not in the correct format.", dateString);
  }