Can't bind CalendarDatePicker to a model in Xaml UWP

只愿长相守 提交于 2019-12-04 06:46:19

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/41962310/cant-bind-calendardatepicker-to-a-model-in-xaml-uwp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!