Date is not changing in the datepicker xamarin forms

Date is always set to date of today and not listening to the change

this is the view model

   public TaskReportViewModel()
    {
        from = System.DateTime.Now.ToString("yyyy-MM-dd");

        to = System.DateTime.Now.ToString("yyyy-MM-dd");
    }

    public string _to;

    public string to
    {
        get { return _to; }
        set
        {
            _to = value;
            OnPropertyChange("to");
        }
    }

and this is the view

    <DatePicker x:Name="dateFrom" Date="{Binding from}" 
      HorizontalOptions="StartAndExpand" WidthRequest="300" Margin="8" 
            DateSelected="dateFrom_DateSelected">
            <DatePicker.Format>yyyy-MM-dd</DatePicker.Format>
        </DatePicker>

this the page class

        this.BindingContext = new TaskReportViewModel();

        dateFrom.Format = "yyyy-MM-dd";
        dateFrom.BindingContext = new TaskReportViewModel();

        dateTo.Format = "yyyy-MM-dd";
        dateTo.BindingContext = new TaskReportViewModel();

1 answer

  • answered 2019-03-20 12:47 G.hakim

    The reason it is not working is that you are binding a string type to a DateTime type what you should be doing instead is something like this :

    First, you need to add a property like this:

    private DateTime _toDateTime = DateTime.Now;
    public DateTime ToDateTime
        {
            get { return _toDateTime; }
            set { _toDateTime = value; OnPropertyChanged(nameof(ToDateTime)); }
        }
    

    And then change the DatePicker as shown here:

         <DatePicker x:Name="dateFrom" Date="{Binding ToDateTime, Mode=TwoWay}" 
      HorizontalOptions="StartAndExpand" WidthRequest="300" Margin="8" 
            DateSelected="dateFrom_DateSelected">
                        <DatePicker.Format>yyyy-MM-dd</DatePicker.Format>
         </DatePicker>