繁体   English   中英

如何使DateTime属性绑定的TextBox在WPF C#中以dd-mm-yyyy格式读取日期?

[英]How to make a DateTime Property binded TextBox read a date in dd-mm-yyyy format in wpf c#?

我在WPF中有一个TextBox绑定到DateTime属性。 每当用户在该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日。

您应该在数据绑定属性设置器或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);
  } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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