How to get the start and end date of the selected range in Xamarin.Forms Calendar (SfCalendar)
You can get the StartDate and EndDate of the selected range by using the SelectedRange property of SfCalendar.
C#
Declared SelectedRange in ViewModel of type Calendar SelectedRange
public class CalendarViewmodel
{
public SelectionRange SelectedRange { get; set; }
public CalendarViewmodel()
{
}
}
XAML
Bind the SelectionRange with ViewModel SelectedRange property and set the mode as TwoWay.
<ContentPage.BindingContext>
<local:CalendarViewmodel x:Name="viewModel"/>
</ContentPage.BindingContext>
<ContentPage.Content>
<Grid>
<calendar:SfCalendar x:Name="calendar" SelectionMode="RangeSelection" SelectedRange="{Binding SelectedRange ,Mode=TwoWay}" />
</Grid>
</ContentPage.Content>
<ContentPage.Behaviors>
<local:CalendarBehavior/>
</ContentPage.Behaviors>
</ContentPage>
C#
In SelectionChanged event, you can get the StartDate and EndDate of the selected range by using the SelectedRange property.
public class CalendarBehavior : Behavior<ContentPage>
{
SfCalendar calendar;
CalendarViewmodel viewModel;
private DateTime startDate;
private DateTime endDate;
protected override void OnAttachedTo(ContentPage bindable)
{
base.OnAttachedTo(bindable);
this.calendar = bindable.Content.FindByName<SfCalendar>("calendar");
this.viewModel = bindable.Content.FindByName<CalendarViewmodel>("viewModel");
this.WireEvents();
}
private void WireEvents()
{
this.calendar.SelectionChanged += Calendar_SelectionChanged;
}
private void Calendar_SelectionChanged(object sender, Syncfusion.SfCalendar.XForms.SelectionChangedEventArgs e)
{
if (this.calendar.SelectedRange != null)
{
startDate = viewModel.SelectedRange.StartDate;
endDate = viewModel.SelectedRange.EndDate;
App.Current.MainPage.DisplayAlert("StartDate" + " " + ":"+" "+ startDate.ToString(), "EndDate" + " " + ":"+" " + endDate.ToString(),"OK");
}
}
protected override void OnDetachingFrom(ContentPage bindable)
{
base.OnDetachingFrom(bindable);
this.UnWireEvents();
}
private void UnWireEvents()
{
this.calendar.SelectionChanged += Calendar_SelectionChanged;
}
}
