I working on a app that needs dynamic fields for filling form. this form may contains multiple timesheets and each timesheet include startDate and finishDate. so how can set property_change on datepicker that creates on runtime?
if (field.Type == "Timesheets"){
DatePicker sDate = new DatePicker();
sDate.StyleId = field.Name;
sDate.PropertyChanged = sDate_changed;
DatePicker fDate = new DatePicker();
fDate.StyleId = field.Name;
sDate.PropertyChanged = fDate_changed;
}
private async void sDate_changed(object sender, PropertyChangedEventArgs e)
{
// here I don't have access to sdate and fdate
}
CodePudding user response:
that is what the sender
parameter does
private async void sDate_changed(object sender, PropertyChangedEventArgs e)
{
var picker = (DatePicker)sender;
// now you can access all the properties of the picker
}
CodePudding user response:
After checking your code, I recommend you to add event DateSelected
for your DatePicker.
replace code:
sDate.PropertyChanged = sDate_changed;
fDate.PropertyChanged = fDate_changed;
with:
sDate.DateSelected = SDate_DateSelected;
fDate.DateSelected = FDate_DateSelected;
// here I don't have access to sdate and fdate
There are two ways to access sdate
and fdate
.
Method 1(just as Jason posted):
async void SDate_DateSelected(object sender, DateChangedEventArgs e)
{
var picker = (DatePicker)sender;
await DisplayAlert("Alert", "selected date is: " picker.Date, "OK");
}
Method 2:
Since you have defined new variables for two DatePicker
(sdate
and fdate
) , you can use the two variables(sdate
and fdate
) to access the selected date.
Please refer to the following code:
sDate.DateSelected = SDate_DateSelected;
fDate.DateSelected = FDate_DateSelected;
//method 2
void Recalculate()
{
TimeSpan timeSpan = fDate.Date - sDate.Date;
mLabel.Text = String.Format("{0} day{1} between dates",
timeSpan.Days, timeSpan.Days == 1 ? "" : "s");
}
async void SDate_DateSelected(object sender, DateChangedEventArgs e)
{
var picker = (DatePicker)sender;
await DisplayAlert("Alert", "SDate_DateSelected : " picker.Date, "OK");
//Recalculate();
}
async void FDate_DateSelected(object sender, DateChangedEventArgs e)
{
var picker = (DatePicker)sender;
await DisplayAlert("Alert", " FDate_DateSelected : " picker.Date, "OK");
//Recalculate();
}
Note:
I find that your code variable is being used incorrectly,please replace the following code:
DatePicker fDate = new DatePicker();
fDate.StyleId = field.Name;
sDate.PropertyChanged = fDate_changed;
with
DatePicker fDate = new DatePicker();
fDate.StyleId = field.Name;
// here it should be fDate not sDate
fDate.PropertyChanged = fDate_changed;