【问题标题】:DatePicker Value cannot be converted. when date format is dd/MM/yyyyDatePicker 值无法转换。当日期格式为 dd/MM/yyyy
【发布时间】:2021-02-25 16:06:46
【问题描述】:

我正在使用带有 MVVM 模式的 WPF,我在 XAML 中有一个 DatePicker,如下所示:

<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# wpf xaml mvvm


    【解决方案1】:

    问题是您绑定了错误的属性。您的 FCGene 属性属于 DateTime 类型,但您将其绑定到 DateTimePickerText 属性,该属性需要 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" />
    

    【讨论】:

      猜你喜欢
      • 2011-02-09
      • 2017-06-24
      • 1970-01-01
      • 2012-05-05
      • 1970-01-01
      • 2023-03-15
      • 2022-11-17
      • 2011-11-25
      • 1970-01-01
      相关资源
      最近更新 更多