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:
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:
Try-catch inside ExecuteFunction.
set a breakpoint, find out what value that bad date is. Add a test to skip ExecuteFunction when that value is seen.
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();
}
}