2

I have model class in shared PCL (for android and uwp app) that contain datetime property:

public class Meter {
        public int meter_value {get; set; }    
        public DateTime meter_start { get; set; }
        public DateTime meter_end { get; set; }
... other int and string properties
}

In MainPage.cs i have

public Meter _meter;
public MainPage()
{
    this.InitializeComponent();
    _meter = new Meter();
}

I'm trying to bind this to a xaml controls with following code:

   <TextBox 
      Text="{x:Bind _meter.meter_value, Mode=TwoWay}">

   <CalendarDatePicker 
     Name="meter_start"
      Date="{x:Bind _meter.meter_start, Mode=TwoWay}"
      DateFormat="{}{day.integer}/{month.integer}/{year.full}" >
   </CalendarDatePicker>

This code produce compile time error: Invalid binding path '_meter.meter_start' : Cannot bind type 'System.DateTime' to 'System.Nullable(System.DateTimeOffset)' without a converter

When i change x:Bind to Binding, applicaton compile, but value of meter_start property in my model is 0001/01/01.

Can someone help me how to solve this?

onedevteam.com
  • 3,838
  • 10
  • 41
  • 74

1 Answers1

10

As the error says you need a converter - CalendarPicker.Date is of type Nullable<DateTimeOffset> and your property is DateTime. Here is a simple example I've tested - in the code:

public class TimeConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        return new DateTimeOffset(((DateTime)value).ToUniversalTime());

    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        return ((DateTimeOffset)value).DateTime;
    }
}

and in XAML:

<Page.Resources>
    <local:TimeConverter x:Key="TimeConverter"/>
</Page.Resources>

... later
<CalendarDatePicker Name="meter_start" Date="{x:Bind _meter.meter_start, Mode=TwoWay, Converter={StaticResource TimeConverter}}"
                     DateFormat="{}{day.integer}/{month.integer}/{year.full}"/>

You may think of implementing INotifyPropertyChanged and raise the PropertyChanged event, if you also change the _meter from code somewhere.

Note also that when you deal with DateTime and DateTimeOffset, you need to take care of suitable conversion (time zones etc.). You will find some more info at this SO question.

Community
  • 1
  • 1
Romasz
  • 29,662
  • 13
  • 79
  • 154
  • If i do all of that in my model, will it break android portability of my shared PCL? Meter class is shared between UWP and Android platforms.. – onedevteam.com Jan 31 '17 at 16:31
  • 1
    Is this definitely the case? The OP is binding to "_meter.meter_start" which is a property. I see no reason why the parent object has to be a property? –  Jan 31 '17 at 16:54
  • You are right it doesn't have to be a property, though without RaisingProperty the UI won't know about the change. But the problem is with converter rather than this. – Romasz Jan 31 '17 at 17:06