Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converter failed to convert value of type 'system.datetime' to type 'datetime' in windows phone 8.1 Datepicker

I am creating a windows phone 8.1 app using MVVM pattern. I have used datepicker, and I want to get the value(date) of the datepicker in the viewModel, so I have binded this with a property in the viewModel. After running this app I am getting an error in the output window of Visual Studio.

Error: Converter failed to convert value of type 'System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' to type 'DateTime'; BindingExpression: Path='Date' DataItem='App1.ViewModel.MainViewModel'; target element is 'Windows.UI.Xaml.Controls.DatePicker' (Name='null'); target property is 'Date' (type 'DateTime').

Here is my, Xaml view:

<DatePicker Grid.Row="1" Grid.Column="1"
                VerticalContentAlignment="Center"
                HorizontalContentAlignment="Center"
                HorizontalAlignment="Left"
                VerticalAlignment="Center" Margin="26,-0.333,0,0.5"
                Date="{Binding Date}"
                />

ViewModel Property:

 private DateTime _date;
    public DateTime Date
    {
        get { return _date; }
        set
        {
            _date = value; 
            RaisePropertyChanged();
        }
    }

Can anyone help me in solving this error.

like image 999
Utsav Dawn Avatar asked Mar 17 '23 02:03

Utsav Dawn


1 Answers

The Date property of the DatePicker is a DateTimeOffset (MSDN)

That means you can't directly bind it to a DateTime object, as no conversion exists. However, DateTimeOffset has a convienent property, DateTime (MSDN) that is a DateTime.

So just change your binding to:

Date="{Binding Date.DateTime}"

Or bind against a DateTimeOffset property and convert it yourself later.

like image 60
BradleyDotNET Avatar answered Mar 19 '23 14:03

BradleyDotNET