首页 > 解决方案 > DatePicker 值无法转换。当日期格式为 dd/MM/yyyy

问题描述

我正在使用带有 MVVM 模式的 WPF,我DatePicker在 XAML 中有这样的:

<DatePicker Text="{Binding FCGene,Mode=TwoWay}"  SelectedDateFormat="Short" />

在视图的构造函数和视图模型的构造函数中,我设置了这样的文化

CultureInfo ci = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name);
ci.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
ci.DateTimeFormat.LongDatePattern = "dd/MM/yyyy HH:mm:ss";
Thread.CurrentThread.CurrentCulture = ci;

当我选择一个日期时,13/02/2021我得到了这个错误:

“价值无法转换”

DatePicker文本框的正下方,我以dd/MM/yyyy我想要的格式看到文本框中的日期。我想问题出在绑定中,在属性的分配中,在我的视图模型中,我的属性是这样的:

private DateTime fcGene;
public DateTime FCGene
{
    get { return fcGene; }
    set { SetProperty(ref fcGene, value); }
}

标签: c#wpfxamlmvvm

解决方案


问题是您绑定了错误的属性。您的FCGene属性是 type DateTime,但您将其绑定到 的Text属性DateTimePicker,该属性需要 a string,因此转换失败。

获取 DatePicker 显示的文本,或设置选定的日期。

public string Text { get; set; }

要使其与该DateTime属性一起使用,请改为绑定该SelectedDate属性。

<DatePicker SelectedDate="{Binding FCGene, Mode=TwoWay}" SelectedDateFormat="Short" />

如果要绑定Text,则将属性类型更改为string.

private string fcGene;
public string FCGene
{
    get { return fcGene; }
    set { SetProperty(ref fcGene, value); }
}
<DatePicker Text="{Binding FCGene, Mode=TwoWay}" SelectedDateFormat="Short" />

推荐阅读