Home > Blockchain >  Can't invoke function when changing Date property in DatePicker - Xamarin.Forms
Can't invoke function when changing Date property in DatePicker - Xamarin.Forms

Time:06-29

I have a date picker in my view:

<DatePicker MinimumDate="{Binding Today}" Date="{Binding SelectedDate, Mode=TwoWay}"/>

And in my viewModel class i have these two properties:

private DateTime selectedDate;
    public DateTime SelectedDate
    {
        get { return selectedDate; }
        set
        {
            selectedDate = value;             
            OnPropertyChanged(nameof(SelectedDate));
            //ExecuteFunction();
        }
    }

    private DateTime today;
    public DateTime Today
    {
        get { return today; }
        set
        {
            today = value;
            OnPropertyChanged(nameof(Today));
            ExecuteFunction();
        }
    }

I want to execute a function when my SelectedDate changes (when the user chooses the date) but i get this error:

enter image description here

However, i can execute the same function when its only in the "Today" property (i did that for testing). Anyone know why this happens?

Thanks!

CodePudding user response:

This only happens when the page loads for the first time with this code the function is not be called when it loads for the first time.

private bool First { get; set; } = true;

    private DateTime selectedDate;
    public DateTime SelectedDate
    {
        get { return selectedDate; }
        set
        {
            selectedDate= value;             
            OnPropertyChanged(nameof(SelectedDate));

            if (!First)
            {
                ExecuteFunction();
            }
            else
            {
                First = false;
            }
        }
    }

CodePudding user response:

Now that you have isolated the problem, a better fix is to change ExecuteFunction so it copes with a bad date. OR don't call ExecuteFunction when the date is bad.

Several possible ways to fix:

  1. Try-catch inside ExecuteFunction.

  2. set a breakpoint, find out what value that bad date is. Add a test to skip ExecuteFunction when that value is seen.

  3. Since it happens during InitializeComponent, that means xaml is setting it - almost certainly setting it to the value it already has - so you could change SelectedDate setter to:

set
{
    if (selectedDate != value)
    {
        selectedDate = value;             
        OnPropertyChanged(nameof(SelectedDate));
        ExecuteFunction();
    }
}
  • Related